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

字符串按单词逆序

时间:2019-09-22 21:48:21      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:xpl   div   should   arch   you   pre   字符串   tput   search   

leetcode 151. https://leetcode.com/problems/reverse-words-in-a-string/

Example 1:

Input: "the sky is blue"
Output: "blue is sky the"

Example 2:

Input: "  hello world!  "
Output: "world! hello"
Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:

Input: "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

基本思想为,先逆序整个字符串,然后逆序每个单词。在这个过程中处理多余的空格。In-place算法
class Solution {
public:
    string reverseWords(string s) {
        // reverse whole string
        reverse(s.begin(), s.end());
        // reverse each word
        int i = 0,j = 0, storedIndex = 0;
        while (i < s.size()){
            // put i to the first letter of a word
            while (i < s.size() && s[i] == ‘ ‘) ++i;
            // add a space if this is not the first and last word
            if (i < s.size() && storedIndex != 0) s[storedIndex++] = ‘ ‘;
            j = i;
            // put j to the end of the word
            while (j < s.size() && s[j] != ‘ ‘) ++j;
            // reverse this word. There may be spaces in front of the word, and after reverse it goes to the end.
            // if s contains only space, i == j, reverse will do nothing
            reverse(s.begin()+storedIndex, s.begin()+j);
            // put stored index to the end of the word
            storedIndex += j - i;
            // put i to the start of next search
            i = j;
        }
        // finally, storedIndex will point to the letter next to the last word
        s.erase(s.begin()+storedIndex, s.end());
        return s;
    }
};

  

字符串按单词逆序

标签:xpl   div   should   arch   you   pre   字符串   tput   search   

原文地址:https://www.cnblogs.com/vimery/p/11569204.html

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