您的位置:首页 > 其它

02.最长公共前缀(leetcode T14)

2019-03-13 21:54 281 查看

题目:

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: [“flower”,“flow”,“flight”]
Output: “fl”

Example 2:
Input: [“dog”,“racecar”,“car”]
Output: “”
Explanation: There is no common prefix among the input strings.

解题思路:

(1)水平扫描法:

  • 从前往后枚举字符串的每一列,先比较每个字符串的相同列上的字符,再比较下一列;
  • n个字符串的最长公共前缀,也是第一个字符串和第二个字符串的公共前缀,是之与第三个公共前缀,以此类推;
  • 时间复杂度O(s)。
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string word;//存放最大公共前缀
if(strs.size() <= 0)
return "";
for(int i = 0; i < strs[0].length();i++){
char c = strs[0][i];
for(int j = 1; j < strs.size(); j++){
if(i == strs[j].length() || strs[j][i] != c)
return strs[0].substr(0,i);
}
}
return strs[0];
}
};

(2)分治技巧+递归

  • 先将n个字符串分成两半,分别求两半的最长公共前缀,即lcpLeft和lcpRight(递归),最后比较这两个字符串的公共前缀
  • 时间复杂度O(s),空间复杂度O(mlogn)(递归,栈的调用)。

(3)二分法

  • 所有字符串的公共前缀,最长是所有字符串最短的长度;
  • 每一次查找将字符串二分,丢弃一定不包含答案的那一半。

新的学习内容:

1.c++的string类

2.c++的容器vector

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: