Article Directory
Title description
Direct thinking
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs==null||strs.length<1){
return "";
}
if(strs.length==1){
return strs[0];
}
int start = 0;
while(start<strs[0].length()) {
for (int i = 1; i < strs.length; i++) {
if(start>=strs[i].length())/*aa,a的情况*/
return strs[0].substring(0, start);
if (strs[i].charAt(start) != strs[0].charAt(start))
return strs[0].substring(0, start);
}
start++;
}
return strs[0].substring(0,start);
}
}
Complexity analysis:
Time complexity: O(mn), where m is the average length of the strings in the string array, and n is the number of strings. In the worst case, each character of each string in the string array will be compared once.
Space complexity: O(1). The extra space complexity used is constant.
Strange submission result:
Precautions:
- 1. Boundary issues
- 2. Array out of bounds problem