【leetcode】P14LongestCommonPrefix
//編寫一個函式來查詢字串陣列中的最長公共字首。
//
// 如果不存在公共字首,返回空字串 ""。
//
// 示例 1:
//
// 輸入: ["flower","flow","flight"]
//輸出: "fl"
//
//
// 示例 2:
//
// 輸入: ["dog","racecar","car"]
//輸出: ""
//解釋: 輸入不存在公共字首。
//
//
// 說明:
//
// 所有輸入只包含小寫字母 a-z 。
// Related Topics 字串
// ? 1328 ? 0
package leetcode.editor.cn;
//Java:最長公共字首
public class P14LongestCommonPrefix {
public static void main(String[] args) {
Solution solution = new P14LongestCommonPrefix().new Solution();
// TO TEST
String[] strs = {"flower", "flow", "flight"};
String s = solution.longestCommonPrefix(strs);
System.out.println(s);
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0)
return "";
int index = 0;
int maxIndex = getMinLen(strs);
StringBuilder stringBuilder = new StringBuilder();
while (index < maxIndex) {
char curChar = strs[0].charAt(index);
for (int i = 1; i < strs.length; i++) {
if (strs[i].charAt(index) != curChar)
return stringBuilder.toString();
}
stringBuilder.append(curChar);
index++;
}
return stringBuilder.toString();
}
public int getMinLen(String[] strs) {
int minLen = strs[0].length();
for (int i = 1; i < strs.length; i++) {
minLen = strs[i].length() < minLen ? strs[i].length() : minLen;
}
return minLen;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
時間複雜度O(mn),其中m為字串平均長度,空間複雜度O(1)
其他思路
- 橫向搜尋,求1,2的最長公共字首,得到結果和3繼續求字首,遍歷到最後一個字串,時間複雜度O(mn)
- 遞迴,字元陣列拆成兩半,分別求左右兩半的公共字首,再合併求最終的公共字首,遞迴出口為當前拆分的字串數量為1,時間複雜度O(n)
相關文章
- 【LeetCode】如何學習LeetCode?LeetCode
- LeetCodeLeetCode
- LeetCode in actionLeetCode
- Leetcode AnagramsLeetCode
- Leetcode SortListLeetCode
- Leetcode ReorderListLeetCode
- leetcode SubsetsLeetCode
- Leetcode PermutationsLeetCode
- [LeetCode刷題筆記] 關於LeetCode的前言LeetCode筆記
- 我的 LeetCodeLeetCode
- Leetcode學習LeetCode
- LeetCode 53 JSLeetCodeJS
- LeetCode 50 JSLeetCodeJS
- LeetCode 克隆圖LeetCode
- Leetcode Perfect SquaresLeetCode
- Leetcode Sort ColorsLeetCode
- Leetcode Sort ArrayLeetCode
- 【LeetCode】Jewels and StonesLeetCode
- 嘗試 LeetcodeLeetCode
- LeetCode 消除遊戲LeetCode遊戲
- Leetcode03LeetCode
- Leetcode LRU CacheLeetCode
- Leetcode Path SumLeetCode
- LeetCode Min StackLeetCode
- Leetcode Word SearchLeetCode
- Leetcode Number of islandsLeetCode
- Leetcode-394LeetCode
- Leetcode 921 JavascriptLeetCodeJavaScript
- golang刷leetcodeGolangLeetCode
- LeetCode:快速排序LeetCode排序
- [LeetCode] Group AnagramLeetCode
- leetcode690LeetCode
- LeetCode 283 jsLeetCodeJS
- Leetcode #463 JavascriptLeetCodeJavaScript
- Leetcode # 495 JavascriptLeetCodeJavaScript
- Leetcode 513 javascriptLeetCodeJavaScript
- Leetcode725LeetCode
- Leetcode目錄LeetCode