【字符串】14. 最长公共前缀

题目:

解答:

方法一:

首先找出最短字符串,然后一个一个匹配。

具体代码如下:

 1 class Solution
 2 {
 3 public:
 4     string longestCommonPrefix(vector<string> &strs)
 5     {
 6         if(strs.size() == 0)
 7         {
 8             return "";
 9         }
10         string prefix = "";
11         int minlen = strs[0].size();
12         
13         //找到最短的字符串
14         for(int istr = 1; istr < strs.size(); istr++)
15         {
16             string str = strs[istr];
17             if(str.size() < minlen)
18             {
19                 minlen = str.size();
20             }
21         }
22         for(int i = 0; i < minlen; i++)
23         {
24             string firststr = strs[0];
25             char firstchar = firststr[i];
26             for(int istr = 1; istr < strs.size(); istr++)
27             {
28                 string str = strs[istr];
29                 if(str[i] != firstchar)
30                 {
31                     return prefix;
32                 }
33             }
34             prefix += firstchar;
35         }
36         return prefix;
37     }
38 };

方法二:

The idea is to maintain a rightmost index so far and scan through the array. Is there a faster algorithm?

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

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12822606.html