Skip to content

Latest commit

 

History

History
63 lines (51 loc) · 1.56 KB

0151._Reverse_Words_in_a_String.md

File metadata and controls

63 lines (51 loc) · 1.56 KB

151. Reverse Words in a String

难度:Medium

刷题内容

原题连接

内容描述

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.

思路 - 时间复杂度: O(N)- 空间复杂度: O(N)******

倒着比遍历数组,遇到空格就认为是一个单词,注意对于边界条件的判断,在开一个新的 string 储存刚刚的单词,最后赋值给 s。总的来说不难。但是还是有一点小陷阱的,单词之间的空格可以是多个的,字符串的开头和末尾也可以有多个空格。需要写个循环清除空格。

class Solution {
public:
    void reverseWords(string &s) {
        int i = 0,j = s.length();
        while(i < j && s[i] == ' ')
            i++;
        j--;
        while(j >= i && s[j] == ' ')
            j--;
        j++;
        string s1;
        while(j >= i)
        {
            int temp = j - 1;
            while(temp >= 0 && s[temp] != ' ')
                temp--;
            int t = temp;
            temp++;
            while(j > temp)
                s1.push_back(s[temp++]);
            j = t - 1;
            while(j >= i && s[j] == ' ')
                j--;
            j++;
            if(j >= i)
                s1.push_back(' ');
        }
        s = s1;
    }
};