[Leetcode] Reverse String

lkimilhol·2021년 3월 20일
0

코딩테스트

목록 보기
8/8

https://leetcode.com/problems/reverse-string/

Write a function that reverses a string. The input string is given as an array of characters s.

주어진 배열을 뒤짚는 문제입니다.

문제에 제약 사항이 하나가 있는데요. 바로 아래 내용입니다.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

새로운 배열을 만들어서 하지 말라는 내용입니다.

그럼 어떻게 해야할까요?

일단 배열의 커서 2개를 만듭니다.

하나는 시작부터 하나는 제일 끝부터 입니다.

반복문을 통해 시작과 끝의 커서는 이동을 시작하게 됩니다. 그리고 이 값들에 조건을 걸건데요. 바로 시작하는 커서가 제일 끝의 커서보다 값이 커지면 멈출겁니다.

그리고 반복문 안에서는 변수 하나를 선언해서. 처음과 끝을 swap 합니다. 다음은 두번째, 그리고 제일 끝에서 두번째를 swap 하면 됩니다.

public class ReverseString {
    public void solution(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--;
        }
    }
}
profile
백엔드 개발자

0개의 댓글