请设计一个高效算法,再给定的字符串数组中,找到包含”Coder”的字符串(不区分大小写),并将其作为一个新的数组返回。结果字符串的顺序按照”Coder”出现的次数递减排列,若两个串中”Coder”出现的次数相同,则保持他们在原数组中的位置关系。
给定一个字符串数组A和它的大小n,请返回结果数组。保证原数组大小小于等于300,其中每个串的长度小于等于200。同时保证一定存在包含coder的字符串。
测试样例:
[“i am a coder”,”Coder Coder”,”Code”],3
返回:[“Coder Coder”,”i am a coder”]
#include<iostream>
#include<vector>
#include<string>
#include<cctype>
#include<algorithm>
using namespace std;
bool cmp(pair<string, int>a, pair<string, int>b)
{
return a.second > b.second;
}
class Coder
{
public:
string change(string &str)
{
string temp = str;
for (int i = 0; i < (int)str.size(); ++i)
if (isupper(temp[i]))
temp[i] = temp[i] + 32;
return temp;
}
vector<string> findCoder(vector<string> A, int n)
{
// write code here
vector<pair<string, int>>a;
for (int i = 0; i < n; ++i)
{
string str = change(A[i]);
int count = 0;
int pos = str.find("coder");
while (pos != -1)
{
str = str.substr(pos + 5);
pos = str.find("coder");
count++;
}
if (count)
a.push_back(make_pair(A[i], count));
}
stable_sort(a.begin(), a.end(), cmp);
vector<string> temp;
for (int i = 0; i < (int)a.size(); i++)
temp.push_back(a[i].first);
return temp;
}
};
int main(void)
{
Coder *code = new Coder;
int n;
vector<string>a;
cin >> n;
int tmp = n;
cin.ignore();
while (n--)
{
string tmp;
getline(cin, tmp);
a.push_back(tmp);
}
vector<string>str;
str=code->findCoder(a, tmp);
for (auto temp : str)
cout << temp << endl;
system("pause");
return 0;
}