LeetCode 14. Longest Common Prefix

LeetCode 14. Longest Common Prefix

    • Description
    • Example
    • Note
    • Code
    • Conclusion

Description

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

If there is no common prefix, return an empty string "".

Example

LeetCode 14. Longest Common Prefix_第1张图片

Note

All given inputs are in lowercase letters a-z.

Code

  • java
class Solution {
    public String longestCommonPrefix(String[] strs) {
        int len = strs.length;
        if(len == 0) return "";
        int commonLength = 0;
        int minLength = strs[0].length();
        for(int i = 1; i < len; i++) {
            minLength = Math.min(minLength, strs[i].length());
        }
        for(; commonLength < minLength; commonLength++) {
            char ch = strs[0].charAt(commonLength);
            boolean same = true;
            for(int i = 1; i < len; i++) {
                if(strs[i].charAt(commonLength) != ch) {
                    same = false;
                    break;
                }
            }
            if(!same) break;
        }
        return strs[0].substring(0, commonLength);
    }
}
  • Official solution1
  • 按两个之间比较后得到的结果与下一个字符串继续比较。
 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;
}
  • Official Solution2:Vertical scanning
class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) return "";
        for (int i = 0; i < strs[0].length() ; i++){
            char c = strs[0].charAt(i);
            for (int j = 1; j < strs.length; j ++) {
                if (i == strs[j].length() || strs[j].charAt(i) != c)
                    return strs[0].substring(0, i);             
            }
        }
        return strs[0];
    }
}

Conclusion

  • 有很多种解法,比如二分,归并等

你可能感兴趣的:(LeetCode,LeetCode,Longest,Common,Prefix)