The idea is to take the first as a sample String. Loop through the same String, and inside the loop, compare each char by order with each of the other Strings in the array, see if it matches. If yes, add the char to the result, otherwise exit the loop, return the result.
public class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0){
return "";
}
if(strs.length == 1){
return strs[0];
}
String sample = strs[0];
StringBuilder result = new StringBuilder();
for(int i = 0; i < sample.length(); i++){
boolean isPrefix = true;
for(int j = 1; j < strs.length; j++){
if(i < strs[j].length()){
if(strs[j].charAt(i) != sample.charAt(i)){
isPrefix = false;
}
}else{
isPrefix = false;
break;
}
}
if(isPrefix){
result.append(sample.charAt(i));
}else{
break;
}
}
return result.toString();
}
}
没有评论:
发表评论