less than 1 minute read

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^5
  • s[i] is a printable ascii character.

Solution

Logic

  1. 배열의 첫 번째 요소와 마지막 요소를 바꾼다. 배열의 두 번째 요소와 마지막 전 요소를 바꾼다. …

  2. 위 과정을 배열의 중간 요소까지 진행한다.

    Code

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

    Time Complexity

    • 배열 s의 길이를 n이라 가정했을 때, 코드의 수행 시간을 지배하는 것은 for반복문의 n / 2번 계산 횟수이다. 따라서 본 솔루션은 O(n)의 시간 복잡도를 가진다.

Categories:

Updated:

Leave a comment