Created
November 10, 2024 07:54
-
-
Save sAVItar02/ee0121feff58f61900a4e612a7de8391 to your computer and use it in GitHub Desktop.
Reverse String 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string} s | |
* @param {number} k | |
* @return {string} | |
*/ | |
var reverseStr = function(s, k) { | |
let reverseFrom = (i, j) => { | |
s = s.split(""); | |
while(i<j) { | |
let temp = s[i]; | |
s[i] = s[j]; | |
s[j] = temp; | |
i++; | |
j--; | |
} | |
s = s.join(""); | |
} | |
let i = 0; | |
let shouldReverse = 1; | |
if(s.length <= k) { | |
s = s.split(""); | |
s.reverse(); | |
s = s.join(""); | |
return s; | |
} | |
while(i < s.length - k) { | |
reverseFrom(i, i+k - 1); | |
console.log(s); | |
i = i + 2*k; | |
if(s.length - i <= k) { | |
reverseFrom(i, s.length - 1); | |
} | |
} | |
return s; | |
}; | |
// Function: reverseFrom: Takes 2 arguments, from position and to position, then it reverses that part of the string | |
// run a loop on the string and reverse from i to i+k, then move the i value 2k times ahead to skip the next k characters | |
// if i is less than 2k then reverse first k | |
// if i is less than k then reverse all | |
// Time: O(n) | |
// Space: O(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment