題目描述
編寫一個函數來查找字符串數組中的最長公共前綴。
如果不存在公共前綴,返回空字符串 “”。
示例 1:
輸入: [“flower”,“flow”,“flight”]
輸出: “fl”
示例 2:
輸入: [“dog”,“racecar”,“car”]
輸出: “”
解釋: 輸入不存在公共前綴。
說明:
所有輸入只包含小寫字母 a-z 。
解決方案
class Solution {
public String longestCommonPrefix(String[] strs) {
String result="";
if (strs.length==0) return result;
for (int i = 0; i <strs[0].length() ; i++) {
result+=strs[0].charAt(i);
for (int j = 1; j <strs.length; j++) {
if (!strs[j].startsWith(result)){
return result.substring(0,result.length()-1);
}
}
}
return result;
}
}