【LeetCode】15.Longest Common Prefix

 

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

从字符数组的第一项往后挨个比较。第一次比较后,取第一项与第二项共同的前缀与第三项比较,依此类推。

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if (strs == null || strs.length == 0) return "";
        String s = strs[0];
        for (int i = 1; i < strs.length; i++) {
            int min = Math.min(s.length(), strs[i].length());
            int j = 0;
            while (j < min && s.charAt(j) == strs[i].charAt(j)) { j++; }
            s = s.substring(0, j);
        }
        return s;
    }
    
}

  

posted @ 2013-10-29 22:36  果汁果粒  阅读(182)  评论(0编辑  收藏  举报