码迷,mamicode.com
首页 > 其他好文 > 详细

151 Reverse Words in a String 翻转字符串里的单词

时间:2018-04-06 16:44:35      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:反转字符串   程序   c程序   ret   说明   class   str   http   problem   

给定一个字符串,翻转字符串中的每个单词。
例如,
给定 s = "the sky is blue",
返回 "blue is sky the"。
对于C程序员:请尝试用O(1) 时间复杂度的原地解法。
说明:
    什么构成一个词?
    一系列非空格字符组成一个词。
    输入字符串是否可以包含前导或尾随空格?
    是。但是,您的反转字符串不应包含前导或尾随空格。
    两个单词之间多空格怎么样?
    将它们缩小到反转字符串中的单个空格。
详见:https://leetcode.com/problems/reverse-words-in-a-string/description/

class Solution {
public:
    void reverseWords(string &s) {
        int size=s.size();
        if(size==0||s.empty())
        {
            return;
        }
        reverse(s.begin(),s.end());
        int index=0;
        for(int i=0;i<size;++i)
        {
            if(s[i]!=‘ ‘)
            {
                if(index!=0)
                {
                    s[index++]=‘ ‘;
                }
                int j=i;
                while(j<size&&s[j]!=‘ ‘)
                {
                    s[index++]=s[j++];
                }
                reverse(s.begin()+index-(j-i),s.begin()+index);
            i=j;
            }
        }
        s.resize(index);
    }
};

 

151 Reverse Words in a String 翻转字符串里的单词

标签:反转字符串   程序   c程序   ret   说明   class   str   http   problem   

原文地址:https://www.cnblogs.com/xidian2014/p/8727937.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!