LeetCode 14.
Tags: LeetCode
Complexity
-
Time complexity: O(n)
-
Space complexity: O(1)
Code
class Solution {
public String longestCommonPrefix(String[] strs) {
String pre = strs[0];
int index = 0, len = pre.length();
for (int i=1; i<strs.length; i++) {
len = Math.min(len, strs[i].length());
while (index < len) {
if (pre.charAt(index) != strs[i].charAt(index)) break;
index++;
}
if (index == 0) return "";
pre = pre.substring(0, index);
len = index;
index = 0;
}
return pre;
}
}
Check out the description of this problem at LC 14.