首页 > 代码库 > [LeetCode]14 Longest Common Prefix

[LeetCode]14 Longest Common Prefix

https://oj.leetcode.com/problems/longest-common-prefix/

http://fisherlei.blogspot.com/2012/12/leetcode-longest-common-prefix.html

public class Solution {
    public String longestCommonPrefix(String[] strs)
    {
        // Validations
        if (strs == null || strs.length == 0)
            return "";
            
        if (strs.length == 1)
            return strs[0];

        // Use strs[0] as initial common string.
        String common = strs[0];
    
        // Testify all others
        for (int i = 1 ; i < strs.length ; i ++)
        {
            while (!strs[i].startsWith(common))
            {
                common = common.substring(0, common.length() - 1);
                if (common.isEmpty())
                    return "";
            }
        }
        return common;
    }
}


[LeetCode]14 Longest Common Prefix