넘치게 채우기

[LeetCode] 557. Reverse Words in a String III 본문

PS/LeetCode

[LeetCode] 557. Reverse Words in a String III

riveroverflow 2023. 10. 1. 15:10
728x90
반응형

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

 

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

문제 유형 : 배열, 문자열 처리

문제 난이도 : Easy

 

문제

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

 

문자열 s가 주어진다. 공백으로 구분된 단어들의 순서를 뒤집어서 반환하라.

 

풀이

투 포인터를 이용하여 해결할 수 있다.

1. left를 인덱스0부터, right을 공백이나 배열의 끝이 나오기 전까지 계속 앞으로 보낸다.

2. left와 right범위 사이의 문자열을 뒤집어준다.

3. left = right+2로하여 공백을 건너뛰고 새 단어부터 시작하게 한다.

4. 1~3을 반복한다.

 

코드

C++

class Solution {
public:
    string reverseWords(string s) {
        int left = 0;
        int n = s.size();

        while (left < n) {
            if (s[left] == ' ')
                left++;
            int right = left;

            while (right < n && s[right] != ' ') {
                right++;
                
            }
            right--;

            int start = left, end = right;
            while (start < end) {
                swap(s[start], s[end]);
                start++;
                end--;
            }

            left = right + 2;
        }
        return s;
    }
};

 

728x90
반응형