力扣(LeetCode)试题14-最长公共前缀 C++代码

更新啦,力扣编译可以通过了,最长公共部分待考虑

算法若容器中没有元素,直接返回空

令第一个字符串为初始公共前缀,使用此公共前缀与下一个字符串比较得到新的公共前缀,新公共前缀与再下一个字符串比较…直到和最后一个字符串比较,此时得到的公共前缀就是这些字符串的公共前缀

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 #include <algorithm>
 5 
 6 using namespace std;
 7 
 8 class Solution {
 9 public:
10     string longestCommonPrefix(vector<string>& strs)
11     {
12         string result;
13         if (strs.size() == 0) return "";
14         else
15         {
16             string temp = strs[0];//将第一个串作为公共前缀
17             for (int i = 1; i < strs.size(); i++)//外循环,公共前缀与每个串进行比较
18             {
19                 int min_val = min(temp.length(), strs[i].length());//取公共前缀与下一个串最小值
20                 int index;//索引
21                 if (min_val == 0) return ""; //比较过程中,某个串儿为空,则返回空
22                 else
23                 {
24                     for (int j = 0; j < min_val; j++)
25                     {
26                         if (temp[j] == strs[i][j])
27                         {
28                             index = j;
29                             continue;
30                         }
31                         else
32                         {
33                             temp = temp.substr(0, j);
34                             break;
35                         }
36                     }
37                     temp = temp.substr(0, index + 1);
38                 }
39 
40             }
41             result = temp;//外循环结束,将temp值赋值给result
42 
43         }
44         return result;
45     }
46 };
47 
48 int main(){
49     vector<string> str{ "aa", "a", ""};
50     Solution sol;
51     string result = sol.longestCommonPrefix(str);
52 
53     cout << result << endl;
54 
55     int w;
56     cin >> w;
57     return 0;
58 }

 

 

 

 

 

posted @ 2020-07-01 10:39  ZyLin-ux  阅读(211)  评论(0编辑  收藏  举报