1. 程式人生 > >leetcode刷題之Longest Common Prefix(14)

leetcode刷題之Longest Common Prefix(14)

編寫一個函式來查詢字串陣列中的最長公共字首。

如果不存在公共字首,返回空字串 ""。

示例 1:

輸入: ["flower","flow","flight"]
輸出: "fl"
示例 2:

輸入: ["dog","racecar","car"]
輸出: ""
解釋: 輸入不存在公共字首。
說明:

所有輸入只包含小寫字母 a-z 。

思路:假設第一個字串就是最長字首,依次和剩下的所有字串對比,如果不是的話,依次減去一個字元再迴圈對比一遍,直到找到最大字首或者pre為"",String.indexOf("") = 0

程式碼:

Java

public static String solution(String[] strs){
if(strs == null || strs.length == 0) return "";
String pre = strs[0];
int i = 1;
while(i < strs.length){
while(strs[i].indexOf(pre) != 0) {
pre = pre.substring(0, pre.length() - 1);
}
i++;
}
return pre;
}