思路一:直接思路,每次查看每个字符串元素的对应下标字符是否相同,相同加入结果集中,不同则退出
public class Test14 {
public static void main(String[] args) {
// ["flower","flow","flight"]
String[] strs = { "flower", "flow", "flight" };
System.out.println(longestCommonPrefix(strs));
}
public static String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
int minLength = getMinLength(strs);
StringBuilder result = new StringBuilder();
for (int i = 0; i < minLength; i++) {
char ch = strs[0].charAt(i);
boolean flag = true;
for (int j = 1; j < strs.length; j++) {
if (strs[j].charAt(i) != ch) {
return result.toString();
}
}
if (flag) {
result.append(ch);
}
}
return result.toString();
}
private static int getMinLength(String[] strs) {
int minLength = strs[0].length();
for (String str : strs) {
if (str.length() < minLength) {
minLength = str.length();
}
}
return minLength;
}
}