Longest common prefix
Problem Description
Write a function to find the longest common prefix in an array of strings.
If there is no common prefix, an empty string "" is returned.
Problem-solving ideas
Use the characters of the first string as the benchmark and compare them one by one. If the characters in the corresponding positions of other strings are not equal to the benchmark or the length is not enough, the current result will be returned.
class Solution {
public String longestCommonPrefix(String[] strs) {
int n = strs.length;
String res = "";
if(n == 0) return res;
int j = 0;
while(true){
char temp;
if(strs[0].equals("") || strs[0].length() <= j)
return res;
else
temp = strs[0].charAt(j);
for(int i=1;i<n;i++){
if(strs[i].equals("") || strs[i].length() <= j || strs[i].charAt(j) != temp)
return res;
}
res = res + temp;
j++;
}
}
}