lintcode -- 最长公共前缀

来源:互联网 发布:苹果手机 解压缩软件 编辑:程序博客网 时间:2024/05/21 18:35

给k个字符串,求出他们的最长公共前缀(LCP)

样例

在 "ABCD" "ABEF" 和 "ACEF" 中,  LCP 为 "A"

在 "ABCDEFG", "ABCEFG", "ABCEFA" 中, LCP 为 "ABC"



/*
思路:
1.先获取第一个字符串
2.循环把第一个数和后一个数比较,得到共同字串,
3.再把字串和后一个数拿来比较
*/
public class Solution {
    public String longestCommonPrefix(String[] strs) {
        // write your code here
        if(strs == null || strs.length ==0)return "";
        String com = strs[0];
        for(int i=1;i<strs.length;i++){
            //计数
            int index =0;
            while(index<strs[i].length()&&index<com.length()
                        &&strs[i].charAt(index) == com.charAt(index)){
                //!!不能用if比较strs[i].charAt(index) == com.charAt(index)
                    index++;
            }
            if(index==0)return "";
            ////再求出共同的字串,再去和之后的对比
            com = com.substring(0,index);
        }
        return com;
    }
}