1. 程式人生 > >LeetCode Longest Common Prefix

LeetCode Longest Common Prefix

Problem

Write a function to find the longest common prefix string amongst an array of strings.

就是找出一個字串陣列中元素,最長的通用字首。例如:{“ab”,”abc”,”abd”},答案是 “ab”。

Java 實現


package com.coderli.leetcode.algorithms.easy;

import java.util.Arrays;

/**
 * Write a function to find the longest common prefix string amongst an array of strings.
 *
 * @author li.hzh
 */
public class LongestCommonPrefix { public static void main(String[] args) { LongestCommonPrefix longestCommonPrefix = new LongestCommonPrefix(); System.out.println(longestCommonPrefix.longestCommonPrefix(new String[]{"a"})); System.out.println(longestCommonPrefix.longestCommonPrefix
(new String[]{"a", "ab", "abc"})); System.out.println(longestCommonPrefix.longestCommonPrefix(new String[]{"abc", "ab", "abc"})); System.out.println(longestCommonPrefix.longestCommonPrefix(new String[]{"abd", "ab", "abc"})); System.out.println(longestCommonPrefix.longestCommonPrefix
(new String[]{"a", "b", "c"})); } public String longestCommonPrefix(String[] strs) { if (strs.length == 0) { return ""; } if (strs.length == 1) { return strs[0]; } String result = strs[0]; for (int i = 1; i < strs.length; i++) { String currentStr = strs[i]; int findLength = Math.min(result.length(), currentStr.length()); int commonLength = 0; for (int j = 0; j < findLength; j++) { char charInResult = result.charAt(j); char charInCurrent = currentStr.charAt(j); if (charInResult == charInCurrent) { commonLength++; } else { break; } } result = result.substring(0,commonLength); } return result; } public String longestCommonPrefixBySortFirst(String[] strs) { if (strs.length == 0) { return ""; } if (strs.length == 1) { return strs[0]; } Arrays.sort(strs); String first = strs[0]; String second = strs[strs.length - 1]; String result = first; int commonLength = 0; for (int j = 0; j < first.length(); j++) { char charInFirst = result.charAt(j); char charInSecond = second.charAt(j); if (charInFirst == charInSecond) { commonLength++; } else { break; } } result = result.substring(0,commonLength); return result; } }

分析

這裡提供了兩個解法。第一個解法longestCommonPrefix,應該最容易被想到的解法。就是直接暴力的遍歷陣列元素,拿每個元素跟當前結果做字首比較。找出最新的最大字首。輸出結果。需要注意處理一下邊界值就ok。

提供第二個解法longestCommonPrefixBySortFirst是因為,第一個解法測試雖然通過,但效率不高。因為考慮優化效能,減少遍歷。因此採用先排序再比較的做法。這樣只需要拿排序後的陣列的第一位和最後一位比較即可。減少一次遍歷,但是增加了一次排序損耗。不過快排一般來說是O(nlgn)的,而後一次的遍歷,遍歷的只是陣列最短長度元素的長度,因此提升了一些效率。

最後,我也檢視一下提交裡效率較高解法,主要的優化在於字首計算上。參考程式碼如下:


public String longestCommonPrefix(String[] strs) {
    if (strs.length == 0) return "";
    String prefix = strs[0];
    for (int i = 1; i < strs.length; i++)
        while (strs[i].indexOf(prefix) != 0) {
            prefix = prefix.substring(0, prefix.length() - 1);
            if (prefix.isEmpty()) return "";
        }        
    return prefix;
}