牛克编程-寻找coder

请设计一个高效算法,再给定的字符串数组中,找到包含”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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值