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을 사용하여 left
와 right
가 겹치거나 서로의 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 --;
}
}
}