[leetcode] Reverse String

Harry·2024년 1월 29일
0

leetcode

목록 보기
1/7
post-thumbnail

문제

Write a function that reverses a string. The input string is given as an array of characters s.
You must do this by modifying the input array in-place with O(1) extra memory.

주어진 문자 배열 s를 뒤집는 함수를 작성하는 것이 이번 문제다.
문제 조건은, 오직 O(1)의 메모리 공간을 사용하여 주어진 배열을 수정해야 한다.

풀이 접근 방식

이번 문제에서는 two pointers 방식을 사용했다.
주어진 배열의 첫번째 index를 left, 마지막 index를 right라고 하자.

while loop을 사용하여 leftright가 겹치거나 서로의 index를 넘어가기 전까지 밑 과정을 순서대로 반복하여 left에 위치한 문자와 right에 위치한 문자를 바꾼다.
1. 배열의 right에 위치한 문자를 tmp라는 변수에 넣는다.
2. 배열의 right의 자리에 left에 위치한 문자를 넣는다.
3. 배열의 left의 자리에 tmp에 넣어둔 문자를 넣는다.
4. left를 증가시키고, right를 감소시킨다.

소스코드

class Solution {
    public void reverseString(char[] s) {
        int left = 0, right = s.length - 1;
        while (left < right) {
            
            char tmp = s[right];
            s[right] = s[left];
            s[left] = tmp;
            
            left ++;
            right --;
        }
        
    }
}
profile
A student developer @usyd

0개의 댓글