107 lines
1.6 KiB
Markdown
107 lines
1.6 KiB
Markdown
# 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
|
|
|
|
##### Related topics:
|
|
|
|
##### Links:
|
|
|
|
- [Link to problem](https://leetcode.com/problems/reverse-string/)
|
|
|
|
---
|
|
|
|
### 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](https://en.wikipedia.org/wiki/In-place_algorithm) 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
|
|
|
|
- `1 <= s.length <= 105`
|
|
- `s[i]` is a [printable ascii character](https://en.wikipedia.org/wiki/ASCII#Printable_characters).
|
|
|
|
### 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
|
|
|
|
```cpp
|
|
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
|
|
|
|
```cpp
|
|
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); }
|
|
};
|
|
```
|