首页 > 代码库 > LeetCode --- 14. Longest Common Prefix

LeetCode --- 14. Longest Common Prefix

题目链接:Longest Common Prefix

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

这道题的要求是在字符串数组中找到最长公共前缀。

思路比较简单,就是两个字符串逐个比较,找最长公共子串。这里采用将每个字符串都与第一个字符串相比较,求最长子串。

时间复杂度:O(nm)(n是字符串数组长度,m是字符串长度)

空间复杂度:O(1)

 1 class Solution
 2 {
 3 public:
 4     string longestCommonPrefix(vector<string> &strs)
 5     {
 6         if(strs.size() == 0)
 7             return "";
 8         
 9         string pre = strs[0];
10         for(int i = 1, j; i < strs.size(); ++ i)
11         {
12             for(j = 0; j < pre.size() && j < strs[i].size(); ++ j)
13                 if(pre[j] != strs[i][j])
14                     break;
15             pre = pre.substr(0, j);
16         }
17         return pre;
18     }
19 };

转载请说明出处:LeetCode --- 14. Longest Common Prefix

LeetCode --- 14. Longest Common Prefix