Longest Common Prefix

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

思路

暴力解法, 先找到所有字符里面最小长度(最长的前缀肯定小于等于这个长度).之后循环, 每个以第零个为参照逐位扫描, 如果不相同则返回当前记录的前缀

复杂度

时间O(n)

代码

public class Solution {

public String longestCommonPrefix(String[] strs) {
    if (strs == null || strs.length == 0) {
        return "";
    }
    StringBuilder sb = new StringBuilder();
    int min = Integer.MAX_VALUE;
    for (int i = 0; i < strs.length; i++) {
        if (strs[i].length() < min) {
            min = strs[i].length();
        }
    }
    for (int i = 0; i < min; i++) {
        for (int j = 0; j < strs.length; j++) {
            if (strs[j].charAt(i) != strs[0].charAt(i)) {
                return sb.toString();
            }
        }
        sb.append(strs[0].charAt(i));
    }
    return sb.toString();
}

}


lpy1990
26 声望10 粉丝