Skip to content

0344: Reverse String #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions 0344-Reverse_String/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
let strArray1 = ["h", "e", "l", "l", "o"];
let strArray2 = ["H", "a", "n", "n", "a", "h"];
function reverseStringUsingDestructuring(s) {
let left = 0;
let right = s.length - 1;
while (left < right) {
;
[s[left], s[right]] = [s[right], s[left]];
left++;
right--;
}
}
function reverseStringUsingTempVariable(s) {
let length = s.length;
let left = 0, right = length - 1;
let tempStr;
while (left < right) {
tempStr = s[left];
s[left] = s[right];
s[right] = tempStr;
left++;
right--;
}
}
reverseStringUsingDestructuring(strArray1);
reverseStringUsingTempVariable(strArray2);
console.log(strArray1);
console.log(strArray2);
32 changes: 32 additions & 0 deletions 0344-Reverse_String/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
let strArray1 = ["h", "e", "l", "l", "o"]
let strArray2 = ["H", "a", "n", "n", "a", "h"]

function reverseStringUsingDestructuring(s: string[]): void {
let left = 0
let right = s.length - 1
while (left < right) {
;[s[left], s[right]] = [s[right], s[left]]
left++
right--
}
}

function reverseStringUsingTempVariable(s: string[]): void {
let length: number = s.length
let left: number = 0,
right: number = length - 1
let tempStr: string
while (left < right) {
tempStr = s[left]
s[left] = s[right]
s[right] = tempStr
left++
right--
}
}

reverseStringUsingDestructuring(strArray1)
reverseStringUsingTempVariable(strArray2)

console.log(strArray1)
console.log(strArray2)
18 changes: 18 additions & 0 deletions 0344-Reverse_String/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
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.

Example 1:

> Input: s = ["h","e","l","l","o"]<br>
> Output: ["o","l","l","e","h"]

Example 2:

> Input: s = ["H","a","n","n","a","h"]<br>
> 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).