diff --git a/OJ notes/pages/Leetcode Reverse-String.md b/OJ notes/pages/Leetcode Reverse-String.md new file mode 100644 index 0000000..9a1bfd8 --- /dev/null +++ b/OJ notes/pages/Leetcode Reverse-String.md @@ -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 &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 &s, int l, int r) { + if (l >= r) { + return; + } + + swap(s[l++], s[r--]); + reverse(s, l, r); + } + +public: + void reverseString(vector &s) { reverse(s, 0, s.size() - 1); } +}; +``` \ No newline at end of file diff --git a/OJ notes/pages/Leetcode Reverse-Words-In-a-String.md b/OJ notes/pages/Leetcode Reverse-Words-In-a-String.md new file mode 100644 index 0000000..e69de29 diff --git a/Untitled.md b/Untitled.md new file mode 100644 index 0000000..e69de29