Problem Link
https://leetcode.com/problems/longest-common-prefix/
Detailed Step-by-Step Explanation
https://leetcode.com/problems/longest-common-prefix/solutions/7441779/most-optimal-solution-beats-100-best-app-jxyq

Solution
class Solution {
public String longestCommonPrefix(String[] strs) {
int n = strs.length;
if (strs == null || n == 0) {
return "";
}
String prefix = strs[0];
for (int i = 1; i < n; i++) {
while (strs[i].indexOf(prefix) != 0) {
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) {
return "";
}
}
}
return prefix;
}
}
Top comments (0)