leetcode: Longest Common Prefix

问题描述:

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

原问题链接:https://leetcode.com/problems/longest-common-prefix/

问题分析:

    这个问题相对来说比较好解决。对于一组string来说,我们可以以第一个为基准,然后从它的第一个字符开始去和后面的比较,如果后面所有的string都包含有这个则比较下一个,直到已经达到后面string长度或者后面发现有不匹配的了。

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length < 1) return "";
        StringBuilder builder = new StringBuilder("");
        for(int i = 0; i < strs[0].length(); i++) {
            char c = strs[0].charAt(i);
            for(int j = 1; j < strs.length; j++) {
                if(i >= strs[j].length() || strs[j].charAt(i) != c) {
                    return builder.toString();
                }
            }
            builder.append(c);
        }
        return builder.toString();
    }
}

    这个问题里容易忽略的就是前后字符串的长度可能不一致,另外针对string列表长度也要注意一些特殊情况。

猜你喜欢

转载自shmilyaw-hotmail-com.iteye.com/blog/2278685