Home LeetCode - 151. Reverse Words in a String
Post
Cancel

LeetCode - 151. Reverse Words in a String

151. Reverse Words in a String - medium

문제

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

제한사항

  • 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.

입출력 예

1
2
3
4
Example 1:

Input: "the sky is blue"
Output: "blue is sky the"
1
2
3
4
5
Example 2:

Input: "  hello world!  "
Output: "world! hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
1
2
3
4
5
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.

풀이

  • String
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
    string reverseWords(string s) {
        std::string result;
        std::vector<std::string> v;
        int startIndex = 0;
        
        for (auto i = 0 ;  i < s.size() ; ++i){
            if(s[i+1] == ' ' || i+1 == s.size()){
                std::string sub = s.substr(startIndex, i + 1 - startIndex);
                sub.erase(remove(sub.begin(), sub.end(), ' '), sub.end());

                if (sub.size() != 0) {
                    v.push_back(sub);
                }
                                
                startIndex = i+2;
            }
        }

        for (auto iter = v.rbegin() ; iter != v.rend() ; ++iter) {
            if (iter == v.rend() - 1) {
                result += *iter;            
            } else {
                result += *iter + " ";
            }
        }
        
        return result;
    }
};
This post is licensed under CC BY 4.0 by the author.