14.最長公共前綴
執行用時 :0 ms, 在所有 Java 提交中擊敗了100.00%的用戶
LCS爲這些字符串的最長公共前綴,那麼
隨意取strs[0]
爲初始p,那麼strs[]的最長前綴必是strs[0]
或及其子串,從strs[1]
開始遍歷,找出p
與strs[i]
的最長公共前綴前綴並存到p中。
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length==0)
return "";
String p=strs[0];
for (int i = 1; i <strs.length ; i++) {
while(strs[i].indexOf(p)!=0)
{
p=p.substring(0,p.length()-1);
}
}
return p;
}
}