LeetCode - 最长公共前缀

GitHub:https://github.com/biezhihua/LeetCode

题目

编写一个函数来查找字符串数组中最长的公共前缀字符串。

解法 1 横向扫描法

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

分析:

描述一种简单的方法来查找一组字符串中最长公共前缀:

L C P ( S 1 . . . S n )

也可以将其转换成以下方法:

L C P ( S 1 . . . S 2 ) = L C P ( L C P ( L C P ( S 1 , S 2 ) , S 3 ) , . . . S n )

这里写图片描述

算法

该算法需要遍历字符串数组 [ S 1 . . . S n ] ,在第 i 次遍历过程中查找出 L C P ( S 1 . . . S i ) 的最长公共前缀, 当 L C P ( S 1 . . . S i ) 查找出来的最长公共前缀是空串时,算法结束。否则,经过 n 次遍历,该算法就可以找出 L C P ( S 1 . . . S n ) 的最长公共前缀。

复杂度

  • 空间复杂度:O(1), 仅仅使用常量级别的额外空间。
  • 时间复杂度:O(S)S是字符串数组的所有字符的和。

代码

@Test
public void test() {
    Assert.assertEquals("lee", longestCommonPrefix(new String[]{"leets", "leetcode", "leet", "leets"}));
}

// Horizontal Scanning
public String longestCommonPrefix(String[] strs) {

    if (strs.length == 0) return "";
    String prefix = strs[0];
    for (int i = 1; i < strs.length; i++) {
        // 找出S1与Si间的最长公共字符串
        // indexOf:当存在串时返回>0;不存串时返回-1
        // 只要不存在串,就缩减串的规模,再进行查找
        while (strs[i].indexOf(prefix) != 0) {
            prefix = prefix.substring(0, prefix.length() - 1);
            if (prefix.isEmpty()) return "";
        }
    }
    return prefix;
}

解法2 竖向扫描法

分析:
若是一个很短的串在数组尾部。在上面的方法中,仍需要比较S次。一种优化的方法是按照竖向扫描。在移动到下一列之前,从上到下比较同一列的字符。

代码:

public String longestCommonPrefix(String[] strs) {
   if (strs == null || strs.length == 0) return "";

   for (int i = 0; i < strs[0].length(); i++) {
       // 获得第一行i列的字符
       char c = strs[0].charAt(i);

       // 依次比较剩余行相同列的字符
       for (int j = 1; j < strs.length; j++) {

           // 若j行i列的字符与第一行i列的字符不同,代表最长公共前缀判定结束
           // 若第一行新i列已经超出了剩余行的最大列出,也代表最长公共前缀判定结束
           if (i == strs[j].length() || strs[j].charAt(i) != c)
               return strs[0].subhttps://leetcode.com/problems/longest-common-prefix/solution/string(0, i);
       }
   }
   return strs[0];
}

更多解法

除了上面横向与竖向的解法,还有分治法解法,还有二分搜索解法。

具体的请看这里的讨论。

猜你喜欢

转载自blog.csdn.net/biezhihua/article/details/79859576
今日推荐