leetcode 周赛189 C++按照空格分割 读取单词

库函数

把一行单词 放进数组中
vector< string> word;
stringstream ss(test);
// stringstream ss;
ss<< text;
string temp;
while (ss >> temp)
{
	words.push_back(temp);
}

特别注意 cmp 函数写法

普通写法 定义cmp 函数

1)自定义比较函数cmp

比如:

bool cmp(int a,int b)

{

    return b<a;

}

重载<

bool operator< (const Student& s1, const Student& s2)

{

    if(s1.age==s2.age)

            return s1.name <s2.name;//年龄相同时,按姓名小到大排

    else  return s1.age > s2.age; //从年龄大到小排序

}

class Solution {

public:
struct cmp
{
bool operator() (const string &a, const string &b)
{
return a.size()<b.size();
}
};

定义结构体

struct cmp

{

   bool operator() (const Student& s1, const Student& s2)

   {

          if(s1.age==s2.age)

                 return s1.name <s2.name;

          else  return s1.age < s2.age;

    }

};

public:
    string arrangeWords(string text) {
    stringstream ss;
    ss<< text;
    string temp;

    vector<string> words;

    while(ss>> temp)
    {
        words.push_back(temp);
    }

    if(!words.empty())
    {
        words[0][0]=tolower(words[0][0]);
    }

   
       stable_sort(words.begin(),words.end(),cmp());
    

       string ans="";
       for( auto &s:words)
       {
           ans+=s;
           ans+=" ";
       }

        if(!ans.empty())
            ans[0]=toupper(ans[0]);

        ans.pop_back();

        return ans;
    }

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值