notes/OJ notes/pages/Leetcode Reverse-String.md
2022-09-06 20:22:48 +08:00

1.6 KiB

Leetcode Reverse String

2022-07-12 08:50

Algorithms:

#algorithm #recursion

Data structures:

#DS #array

Difficulty:

#coding_problem #difficulty_easy

Additional tags:

#leetcode

Revisions:

N/A


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.

Examples

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

Thoughts

[!summary] This is a #recursion problem, also can be solved using iteration.

Base case:

  • size <= 1

Pseudo code:

  • swap two ends
  • recurse the sub string(without the ends)

Solution

Iteration

class Solution {
public:
  void reverseString(vector<char> &s) {
    int l = 0, r = s.size() - 1;

    while (l < r) {
      swap(s[l], s[r]);

      l++;
      r--;
    }
  }
};

Recursion

class Solution {
  void reverse(vector<char> &s, int l, int r) {
    if (l >= r) {
      return;
    }

    swap(s[l++], s[r--]);
    reverse(s, l, r);
  }

public:
  void reverseString(vector<char> &s) { reverse(s, 0, s.size() - 1); }
};