翻转字符串

给定一个字符串,逐个翻转字符串中的每个单词。

您在真实的面试中是否遇到过这个题?  
Yes
样例

给出s = "the sky is blue",返回"blue is sky the"

说明

  • 单词的构成:无空格字母构成一个单词
  • 输入字符串是否包括前导或者尾随空格?可以包括,但是反转后的字符不能包括
  • 如何处理两个单词间的多个空格?在反转字符串中间空格减少到只含一个
class Solution {
public:
    /**
     * @param s : A string
     * @return : A string
     */
    string reverseWords(string s) {
        // write your code here
        int n=s.length();
        string res;
        if(n==0) return res;
        for(int i=n-1;i>=0&&s[i]==' ';i--){
            s.erase(s.begin()+i);
        }
        int newn=s.size();if(newn==0) return res;
        for(int i=0;i<newn&&s[i]==' ';i++){
            s.erase(s.begin()+i);
        }
        int newn2=s.length();if(newn==0) return res;
        stack<char>tmp;
        for(int i=newn2-1;i>=0;i--){
            if(s[i]!=' ') tmp.push(s[i]);
            else{
                while(!tmp.empty()){
                    res+=(tmp.top());
                    tmp.pop();
                }
                res+=" ";
            }
            if(i==0&&s[i]!=' '){
                while(!tmp.empty()){
                    res+=(tmp.top());
                    tmp.pop();
                }
            }
        }
        return res.substr(0,newn2);
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值