Leetcode 14 Longest Common Prefix

最长公共子串,我使用的方法是枚举

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

 

posted @ 2016-03-18 21:43  Breeze0806  阅读(134)  评论(0编辑  收藏  举报