Question Link:

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

Question Description

Reverse String in place
Input: s = [“h”,”e”,”l”,”l”,”o”]
Output: [“o”,”l”,”l”,”e”,”h”]

Simulation

Solution 1: Use two pointers to swap values.

Iteration 1: [“h”,”e”,”l”,”l”,”o”] -> [“o”,”e”,”l”,”l”,”h”]
Iteration 2: [“o”,”e”,”l”,”l”,”h”] -> [“o”,”I”,”l”,”e”,”h”]
Iteration 3: [“o”,”I”,”l”,”e”,”h”] -> [“o”,”I”,”l”,”e”,”h”]

Implementation

  1. public void reverseString(char[] s) {
  2. int left = 0, right = s.length - 1;
  3. char temp;
  4. while (left <= right) {
  5. temp = s[left];
  6. s[left] = s[right];
  7. s[right] = temp;
  8. right--;
  9. left++;
  10. }
  11. }