vault backup: 2022-07-12 09:08:19
This commit is contained in:
parent
4c72304a6c
commit
0dd3461bac
101
OJ notes/pages/Leetcode Reverse-String.md
Normal file
101
OJ notes/pages/Leetcode Reverse-String.md
Normal file
|
@ -0,0 +1,101 @@
|
|||
# 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:
|
||||
```expander
|
||||
tag:#recursion
|
||||
```
|
||||
|
||||
- [[Leetcode Insert-Into-a-Binary-Search-Tree]]
|
||||
- [[Leetcode Invert-Binary-Tree]]
|
||||
- [[Leetcode Pascal's-Triangle]]
|
||||
- [[Leetcode Path-Sum]]
|
||||
- [[Leetcode Reverse-Linked-List]]
|
||||
- [[Leetcode Symmetric-Tree]]
|
||||
|
||||
|
||||
##### 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); }
|
||||
};
|
||||
```
|
0
Untitled.md
Normal file
0
Untitled.md
Normal file
Loading…
Reference in a new issue