notes/OJ notes/pages/Leetcode Reverse-String.md

107 lines
1.6 KiB
Markdown
Raw Normal View History

2022-07-12 09:08:19 +08:00
# Leetcode Reverse String
#### 2022-07-12 08:50
> ##### Algorithms:
2022-09-03 15:41:36 +08:00
>
> #algorithm #recursion
>
2022-07-12 09:08:19 +08:00
> ##### Data structures:
2022-09-03 15:41:36 +08:00
>
> #DS #array
>
2022-07-12 09:08:19 +08:00
> ##### Difficulty:
2022-09-03 15:41:36 +08:00
>
2022-09-06 20:22:48 +08:00
> #coding_problem #difficulty_easy
2022-09-03 15:41:36 +08:00
>
2022-07-12 09:08:19 +08:00
> ##### Additional tags:
2022-09-03 15:41:36 +08:00
>
2022-07-12 09:08:19 +08:00
> #leetcode
2022-09-03 15:41:36 +08:00
>
2022-07-12 09:08:19 +08:00
> ##### Revisions:
2022-09-03 15:41:36 +08:00
>
2022-07-12 09:08:19 +08:00
> N/A
##### Related topics:
2022-09-03 15:41:36 +08:00
2022-07-12 09:08:19 +08:00
##### Links:
2022-09-03 15:41:36 +08:00
2022-07-12 09:08:19 +08:00
- [Link to problem](https://leetcode.com/problems/reverse-string/)
2022-09-03 15:41:36 +08:00
---
2022-07-12 09:08:19 +08:00
### 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
2022-09-03 15:41:36 +08:00
- `1 <= s.length <= 105`
- `s[i]` is a [printable ascii character](https://en.wikipedia.org/wiki/ASCII#Printable_characters).
2022-07-12 09:08:19 +08:00
### Thoughts
> [!summary]
> This is a #recursion problem, also can be solved using iteration.
#### Base case:
2022-09-03 15:41:36 +08:00
2022-07-12 09:08:19 +08:00
- size <= 1
2022-09-03 15:41:36 +08:00
2022-07-12 09:08:19 +08:00
#### Pseudo code:
- swap two ends
- recurse the sub string(without the ends)
### Solution
Iteration
2022-09-03 15:41:36 +08:00
2022-07-12 09:08:19 +08:00
```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
2022-09-03 15:41:36 +08:00
2022-07-12 09:08:19 +08:00
```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); }
};
2022-09-03 15:41:36 +08:00
```