Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array,
you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
문자열을 반전시키는 함수를 작성해라. 입력 문자열은 char 타입의 배열로 주어진다.
다른 배열에 추가 공간을 할당하지 말고, 입력 배열을 수정하여 O(1)이 되게끔 하여라.
모든 문자들은 출력이 가능한 아스키 문자로 구성되어있다.
(영알못 주의)
풀이 방법 (two-pointer 사용!)
1. left, right 변수를 선언하여 각각 배열의 시작과 끝 인덱스를 가리키도록 한다.
2. left와 right의 인덱스에 위치하는 문자를 서로 바꾼다.
3. left는 배열의 끝 방향으로(인덱스 증가), right는 배열의 시작 방향으로(인덱스 감소) 증감 시킨다.
4. 반복문의 조건이 (left < right) false가 되기 전까지 계속 반복한다.
class Solution {
public void reverseString(char[] s) {
int left = 0;
int right = s.length - 1;
while(left < right) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
}
'알고리즘 > LeetCode' 카테고리의 다른 글
[JAVA] LeetCode 206 - Reverse Linked List (0) | 2020.11.16 |
---|---|
[JAVA] LeetCode 412 - Fizz Buzz (0) | 2020.11.16 |
[JAVA] LeetCode 237 - Delete Node in a Linked List (0) | 2020.11.14 |
[JAVA] LeetCode 136 - Single Number (0) | 2020.11.14 |
[JAVA] LeetCode 104 - Maximum Depth of Binary Tree (0) | 2020.11.14 |