LeetCode-151-Reverse Words in s String

Posted 无名路人甲

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-151-Reverse Words in s String相关的知识,希望对你有一定的参考价值。

算法描述:

Given an input string, reverse the string word by word.

Example:  

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

Note:

  • A word is defined as a sequence of non-space characters.
  • Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
  • You need to reduce multiple spaces between two words to a single space in the reversed string.

Follow up: For C programmers, try to solve it in-place in O(1) space.

解题思路:先逐词翻转,再整句翻转。注意去除空格。

void reverseWords(string &s, int i, int j){
    while(i < j){
        char temp = s[i];
        s[i++]=s[j];
        s[j--]=temp;        
    }   
}

void reverseWords(string &s){
    int i = 0;
    int j = 0;
    int l = 0;
    int n = s.size();
    int count = 0;
    while(true){
        while(i < n && s[i] ==  ) i++;
        if(i==n) break;
        if(count) s[j++] =  ;
        l=j;
        while(i < n && s[i]!=  ) {s[j]=s[i]; j++; i++;}
        reverseWords(s,l,j-1);
        count++;
    }
    s.resize(j);
    reverseWords(s,0,j-1);
}

 

以上是关于LeetCode-151-Reverse Words in s String的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-151-Reverse Words in s String

LeetCode151. Reverse Words in a String

刷题-LeetCode151 Reverse Words in a String

Leetcode 151. Reverse Words in a String 解题报告

leetcode 151. Reverse Words in a String --------- java

[LeetCode] 151. Reverse Words in a String 翻转字符串中的单词