最长公共前缀 Longest Common Prefix

题目

编写一个函数来查找字符串数组中的最长公共前缀。

以下为详细说明:

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 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

思路&题解

public String longestCommonPrefix(String[] strs) {
    if(strs.length ==0) {
        return "";
    }
    if(strs.length==1){
        return strs[0];
    }
    String common = strs[0];
    for(int i = 1; i<strs.length;i++) {
        int len = Math.min(strs[i].length(),common.length());
        int end=-1;
        for(int j = 0; j<len;j++){
            if(common.charAt(j)==strs[i].charAt(j)){
                end=j;
            } else{
                break;
            }
        }
        if(end<0){
            return "";
        }
        common = common.substring(0,end+1);
    }
    return common;
}
public String longestCommonPrefix(String[] strs) {
    if(strs.length ==0) {
        return "";
    }
    String common = strs[0];
    for(int i = 1; i<strs.length;i++) {
        while(strs[i].indexOf(common) != 0) {
            common = common.substring(0, common.length()-1);
            if(common==""||common==null){
                return "";
            }
        }

    }
    return common;
}

知识点分析

powered by Gitbook最近更新 2019-03-07

results matching ""

    No results matching ""