Question
Write a function to find the longest common prefix string amongst an array of strings.
*Difficulty: Easy
https://leetcode.com/problems/longest-common-prefix/
My Solution
找最短str,然后一个个字母比
public class Solution {
public String longestCommonPrefix(String[] strs) {
StringBuilder sb = new StringBuilder();
if(strs.length == 0) return "";
if(strs.length == 1) return strs[0];
int minLen = Integer.MAX_VALUE;;
for(int i = 0; i < strs.length; i++){
minLen = Math.min(strs[i].length(), minLen);
}
boolean stop = false;
for(int i = 0; i < minLen; i++){
char c = strs[0].charAt(i);
for(String s : strs){
if(s.charAt(i) != c) {
stop=true;
break;
}
}
if(stop) break;
else sb.append(""+c);
}
return sb.toString();
}
}