[LeetCode] Reverse String

아르당·2026년 1월 6일

LeetCode

목록 보기
78/94
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

문자열을 반전하는 함수를 작성해라. 입력한 문자열은 문자 배열 s로 주어진다.
O(1) 추가 메모리를 사용하여 입력 배열을 제자리에서 수정함으로써 이를 수행해야 한다.

Example

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

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

Constraints

  • 1 <= s.length <= 10^5
  • s[i]는 출력가능한 ascii 문자이다.

Solved

class Solution {
    public void reverseString(char[] s) {
        int a = 0;
        int b = s.length - 1;

        while(a < b){
            char temp = s[b];
            s[b] = s[a];
            s[a] = temp;

            a++;
            b--;
        }
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글