Home LeetCode - 557. Reverse Words in a String III
Post
Cancel

LeetCode - 557. Reverse Words in a String III

557. Reverse Words in a String III - easy

문제

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

제한사항

입출력 예

1
2
3
4
Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

풀이

  • String
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
    string reverseWords(string s) {
        std::string result;
        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);
                std::reverse(sub.begin(), sub.end());
                
                i+1 == s.size() ? result += sub : result += sub + ' ';
                
                startIndex = i+2;
            }
        }
        
        return result;
    }
};
This post is licensed under CC BY 4.0 by the author.