[LeetCode] Longest Common Prefix

441 查看

Problem

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

Note

我的思路是用StringBuilderstrs中的字符串逐个遍历第i位的字符,如果都相同,就把这个字符存入sb,否则返回已有的sb字符串。
注意,第二层for循环的条件:i的值不能大于str.length()-1

Solution

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