[LeetCode] 14. Longest Common Prefix

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

If there is no common prefix, return an empty string "".

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Constraints:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lowercase English letters.

最长公共前缀。

编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""

这个题没有什么比较巧妙的思路,就是暴力搜索。在处理了 corner case 比如 input 为空的情况下,我们找到 input 里面的第一个单词,然后拿着这个单词的每个字母在剩下的其他单词里一个个扫,看其他单词同样位置上的字母是否一样。比如第一个例子,拿到 flower 之后,从 F 开始,看后面每个单词的第一个字母是否是 f,若是则进入下一轮,看所有单词的第二个字母是否都是 L。开始看第三个字母 O 的时候,遍历到 flight 的时候,12行的判断为 false 所以返回了str.slice(0, i),是从第一个字母到第 i - 1 个字母组成的 substring。

时间O(n^2) - n是字母个数

空间O(1)

JavaScript实现

 1 /**
 2  * @param {string[]} strs
 3  * @return {string}
 4  */
 5 var longestCommonPrefix = function longestCommonPrefix(strs) {
 6     // corner case
 7     if (!strs.length) return '';
 8 
 9     // normal case
10     for (let i = 0; i < strs[0].length; i++) {
11         for (let str of strs) {
12             if (str[i] !== strs[0][i]) {
13                 return str.slice(0, i);
14             }
15         }
16     }
17     return strs[0];
18 }

 

Java实现

 1 class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         // corner case
 4         if (strs == null || strs.length == 0) {
 5             return "";
 6         }
 7 
 8         // normal case
 9         String prefix = strs[0];
10         int n = strs.length;
11         for (int i = 1; i < n; i++) {
12             prefix = helper(prefix, strs[i]);
13             if (prefix.length() == 0) {
14                 break;
15             }
16         }
17         return prefix;
18     }
19 
20     private String helper(String s1, String s2) {
21         int len = Math.min(s1.length(), s2.length());
22         int i = 0;
23         while (i < len && s1.charAt(i) == s2.charAt(i)) {
24             i++;
25         }
26         return s1.substring(0, i);
27     }
28 }

 

LeetCode 题目总结

posted @ 2020-02-16 08:38  CNoodle  阅读(443)  评论(0)    收藏  举报