14. Longest Common Prefix

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


class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0)
            return "";
        String pre = strs[0]; //以数组第一个String作为基准
        for (int i = 1; i < strs.length; i++) {
            while (strs[i].indexOf(pre) != 0) //若后面的String不包括第一个String,把第一个String一步步从最后面裁减1
                pre = pre.substring(0, pre.length() - 1);  //pre的最后一个字符被裁了              
        }
        return pre;
    }
}
 
 
posted @ 2019-04-09 16:39  MarkLeeBYR  阅读(114)  评论(0)    收藏  举报