반응형

https://leetcode.com/problems/reverse-words-in-a-string-iii/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

각 단어에 대한 시작/끝 인덱스를 구해주고, 해당 범위에 대해서 역순으로 뒤집어줍니다. 

class Solution {
public:
    string reverseWords(string s) {
        int j = 0;
        for(int i=1; i<s.size(); i++) {
            if(s[i] == ' ') {
                reverse(s, j, i - 1);
                j = i + 1;
            }
        }
        reverse(s, j, s.size() - 1);
        return s;
    }

    void reverse(string& s, int l, int r) {
        int sz = (l + r) / 2 - l;
        for(int i=0; i<=sz; i++) {
            swap(s[l + i], s[r - i]);
        }
    }
};
반응형

'Algorithm' 카테고리의 다른 글

LeetCode 706. Design HashMap  (0) 2023.10.04
LeetCode 1512. Number of Good Pairs  (0) 2023.10.03
LeetCode 389. Find the Difference  (1) 2023.09.25
LeetCode 392. Is Subsequence  (0) 2023.09.23
LeetCode 287. Find the Duplicate Number  (0) 2023.09.20

+ Recent posts