Skip to content

151. Reverse Words in a String

难度:Medium

刷题内容

原题连接

  • https://leetcode.com/problems/reverse-words-in-a-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.

˼· **- ʱ�临�Ӷ�: 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;
    }
};


回到顶部