본문으로 바로가기

Description

주어진 문자배열의 내용을 반전(reverse)시키는 문제입니다.

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.

Example 1:

Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:

Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

Constraints:

Solution 1. Two Pointers - Reverse()

public void reverseString(char[] s) {

    int start = 0;
    int end = s.length-1;
    while(start < end){
        char temp = s[start];
        s[start++] = s[end];
        s[end--] = temp;
    }
}

두개의 포인트를 양끝에 두고 문자열 swap후 한 칸씩 움직이는 것을 반복하여 전체 문자열을 반전시킵니다.

- 시간복잡도 : O(N)
- 공간복잡도 : O(N)

Reference

 

Reverse String - LeetCode

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