Longest Common Prefix字串最長公共字首問題

yushuifirst發表於2015-05-18

Longest Common Prefix字串最長公共字首問題

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

java程式碼

public static String longestCommonPrefix(String[] strs) {
    if(strs.length==0)return "";
    if(strs.length==1)return strs[0];
    int length=0;
    int k=0;
    start:
    while(true){
        char a='a';
        for(int i=0;i<strs.length;i++){
            if(k<strs[i].length()){
                if(i==0){
                    a=strs[i].charAt(k);
                }else{
                    if(a!=strs[i].charAt(k)){
                        break start;
                     }
                }
            }else{
                break start;
            }
        }
        length++;
        k++;
    }
    if(length==0){return "";}
    return strs[0].substring(0,length);
}

相關文章