package com.shengda.Demo0Likou;
public class Demo14 {
public static void main(String[] args) {
Solution s = new Solution();
String[] strs = new String[]{
"ab","ab"};
String str = s.longesCommonPrefix(strs);
System.out.println(str);
}
}
class Solution{
public String longesCommonPrefix(String[] strs) {
if(strs.length == 0){
return "";
}
int j = 0;
String str = strs[0];
for (int i = 0; i < strs.length; i++) {
if ("".equals(strs[i])) return "";
if (strs[i].length()<str.length()) str = strs[i];
}
while (getCommon(strs,str,j)) {
j++;
}
return str.substring(0,j);
}
private boolean getCommon(String[] strs, String str,int j) {
for (int i = 0; i < strs.length; i++) {
if (j == str.length() || strs[i].charAt(j) != str.charAt(j))
return false;
}
return true;
}
}
文章评论