Longest Common Prefix

题目地址:
https://leetcode.com/problems/longest-common-prefix/description/

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

解题思路:
这道题就是双指针问题。

代码:

public String longestCommonPrefix(String[] strs) {
    if(strs == null || strs.length == 0){
        return "";
    }
    String shortest = strs[0];
    for(int i = 1; i <= strs.length - 1; i++){
        if(strs[i].length() < shortest.length()){
            shortest = strs[i];
        }
    }
    String rst = shortest;
    for(int i = 0; i <= strs.length - 1; i++){
        rst = getCommonPrefix(strs[i], rst);
    }
    return rst;
}

private String getCommonPrefix(String str, String rst) {
    if(str == null || rst == null || str.length() == 0 || rst.length() == 0){
        return "";
    }
    StringBuilder sb = new StringBuilder();
    int i = 0;
    while(i <= rst.length() - 1){
        if(str.charAt(i) == rst.charAt(i)){
            sb.append(str.charAt(i));
            i++;
            continue;
        }
        break;
    }
    return sb.toString();
}








Comments

Popular Posts