找出一个字符串数组中最长公共前缀字符串

找出一个字符串数组中最长公共前缀字符串

1.水平扫描

public String longestCommonPrefix(String[] strs) {
    if (strs.length == 0) return "";
    String prefix = strs[0];
    for (int i = 1; i < strs.length; i++)
        while (strs[i].indexOf(prefix) != 0) {                      \\返回一个整数值,指出 String 对象内子字符串的开始位置。如果没有找到子字符串,则返回-1。
            prefix = prefix.substring(0, prefix.length() - 1);      \\子字符串开始位置不为0则缩小子字符串,再进行对比
            if (prefix.isEmpty()) return "";
        }        
    return prefix;
}
  • Time complexity : O(S)O(S) , where S is the sum of all characters in all strings.

In the worst case all nn strings are the same. The algorithm compares the string S1S1 with the other strings [S_2 \ldots S_n][S2Sn] There are SS character comparisons, where S S is the sum of all characters in the input array.

  • Space complexity : O(1)O(1). We only used constant extra space.

2.垂直扫描
Imagine a very short string is at the end of the array. The above approach will still do SS comparisons. One way to optimize this case is to do vertical scanning. We compare characters from top to bottom on the same column (same character index of the strings) before moving on to the next column.

public String longestCommonPrefix(String[] strs) {
    if (strs == null || strs.length == 0) return "";
    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 strs[0].substring(0, i);             
        }
    }
    return strs[0];
}

Complexity Analysis

  • Time complexity : O(S)O(S) , where S is the sum of all characters in all strings. In the worst case there will be nn equal strings with length mm and the algorithm performs S = m*nS=mn character comparisons. Even though the worst case is still the same as Approach #1, in the best case there are at most n*minLennminLencomparisons where minLenminLen is the length of the shortest string in the array.
  • Space complexity : O(1)O(1). We only used constant extra space.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值