寻找Coder-统计一个字符串中另外一个子串的个数

题目描述

请设计一个高效算法,再给定的字符串数组中,找到包含"Coder"的字符串(不区分大小写),并将其作为一个新的数组返回。结果字符串的顺序按照"Coder"出现的次数递减排列,若两个串中"Coder"出现的次数相同,则保持他们在原数组中的位置关系。

给定一个字符串数组A和它的大小n,请返回结果数组。保证原数组大小小于等于300,其中每个串的长度小于等于200。同时保证一定存在包含coder的字符串。

测试样例:
["i am a coder","Coder Coder","Code"],3
返回:["Coder Coder","i am a coder"]

 1 bool cmp(const pair<string,int>p1,const pair<string,int>p2)
 2    {
 3         return p1.second>p2.second;
 4     }
 5 class Coder {
 6 public:
 7    
 8     string tolower(string str)
 9     {
10         string ans=str;
11         for(int i=0;i<str.size();i++)
12         {
13             if(str[i]>='A'&&str[i]<='Z')
14                 ans[i]=str[i]+32;
15         }
16         return ans;
17     }
18    
19     vector<string> findCoder(vector<string> A, int n) {
20         
21         // write code here
22         vector<pair<string,int>>ans;
23         vector<string>result;
24         for(int i=0;i<n;i++)
25         {
26             string str=tolower(A[i]);
27             int count=0;
28             int pos=str.find("coder");
29             while(pos!=-1)//这种find方法统计很好
30             {
31                 str=str.substr(pos+5);
32                 pos=str.find("coder");
33                 count++;
34             }
35             if(count!=0)
36                 ans.push_back(make_pair(A[i],count));
37         }
38         stable_sort(ans.begin(),ans.end(),cmp);
39         for(int i=0;i<ans.size();i++)
40             {
41             result.push_back(ans[i].first);
42         }
43         return result;
44     }
45 };

 

posted @ 2016-08-31 22:50  ranran1203  阅读(834)  评论(0编辑  收藏  举报