字符串按单词逆序

Posted vimery

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字符串按单词逆序相关的知识,希望对你有一定的参考价值。

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;
    
;

  

以上是关于字符串按单词逆序的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode692. 前K个高频单词 / 剑指 Offer 50. 第一个只出现一次的字符 / 剑指 Offer 51. 数组中的逆序对 / 2. 两数相加

C语言写一个函数,实现字符串内单词逆序

java小程序之单词逆序

C语言把一个字符串中的单词逆序(难)

C语言把一个字符串中的单词逆序(难)

LeetCode--058--最后一个单词的长度