[leetcode #344] Reverse String

Seongyeol Shin·2022년 4월 1일
0

leetcode

목록 보기
178/196
post-thumbnail

Problem

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:

· 1 <= s.length <= 10⁵
· s[i] is a printable ascii character.

Idea

주어진 char array의 순서를 거꾸로 하면 되는 문제다.

array의 길이를 우선 저장한 뒤, 그 길이의 1/2만큼 루프를 돌린다. 루프에서 처리하는 연산은 해당 index의 값과 len-1-index의 값을 서로 바꾸는 것이다.

Solution

class Solution {
    public void reverseString(char[] s) {
        int len = s.length;
        for (int i=0; i < len / 2; i++) {
            char tmp = s[i];
            s[i] = s[len-i-1];
            s[len-i-1] = tmp;
        }
    }
}

Reference

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

profile
서버개발자 토모입니다

0개의 댓글