Home LeetCode 344. Reverse String
Post
Cancel

LeetCode 344. Reverse String

344. Reverse String

Problem

1
2
3
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.

Questions before reading example

  1. ”s” can be empty? nope
  2. ”s” max length? 10^5
  3. ”s” only english? yes

Example

1
2
3
4
5
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

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

Solution

1
2
3
4
5
6
7
8
9
10
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;
    }

  }
}

Spent time

  • 13분

Review

  • 생각나는 그대로 풀었는데 다행히 잘 풀렸다.
  • index 를 다루는건 늘 조심스럽다.
This post is licensed under CC BY 4.0 by the author.