码迷,mamicode.com
首页 > 其他好文 > 详细

No.14 Longest Common Prefix

时间:2015-06-10 15:28:49      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

No.14 Longest Common Prefix

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

求一组string的最长公共前缀
想法:找到最短的那个,然后依次对比

 

典型的字符串操作,从前向后比较即可

 

 1 #include "stdafx.h"
 2 #include <string>
 3 #include <vector>
 4 #include <iostream>
 5 #include <algorithm>
 6 using namespace std;
 7 
 8 class Solution
 9 {
10 public:
11     string longestCommonPrefix(vector<string> &strs)
12     {//求一组string的最长公共前缀
13      //想法:找到最短的那个,然后依次对比
14         int size = strs.size();
15         string res("");
16         if(size == 0)
17             return res;
18 
19         int shortestCount = strs[0].size();//记录最短的
20         for(int i=1; i<size; i++)
21         {
22             if(strs[i].size() < shortestCount)
23                 shortestCount = strs[i].size();
24         }
25 
26         //从前向后比较shortestCount位
27         for(int i=0; i<shortestCount; i++)
28         {
29             auto tmp = strs[0][i];
30             for(int j=1; j<size; j++)
31             {
32                 if(strs[j][i] != tmp)
33                     return res;
34             }
35             res += tmp;
36         }
37         return res;
38     }
39 };
40 
41 int main()
42 {
43     Solution sol;
44     string data[] = {"a","abc","ad"};
45     vector<string> test(data,data+3);
46     cout << sol.longestCommonPrefix(test)<<endl;
47 
48     string data1[] = {"ad","abc","ad",""};
49     vector<string> test1(data1,data1+4);
50     cout << sol.longestCommonPrefix(test1)<<endl;
51 }

 

No.14 Longest Common Prefix

标签:

原文地址:http://www.cnblogs.com/dreamrun/p/4566099.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!