Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit eb7ce05

Browse files
Create Reverse_String_II.js
1 parent 5f80dec commit eb7ce05

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

LeetcodeProblems/Reverse_String_II.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
3+
Reverse String II
4+
5+
https://leetcode.com/problems/reverse-string-ii/description/
6+
7+
Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.
8+
Example:
9+
Input: s = "abcdefg", k = 2
10+
Output: "bacdfeg"
11+
Restrictions:
12+
The string consists of lower English letters only.
13+
Length of the given string and k will in the range [1, 10000]
14+
*/
15+
var reverseStr = function(s, k) {
16+
if(k <= 1)
17+
return s;
18+
var ret = "";
19+
for(var iterK = 0; iterK * k < s.length; iterK = iterK + 2) {
20+
const start = iterK * k;
21+
const end = start + k - 1;
22+
23+
ret += reverse(s, start, end);
24+
ret += s.slice(end + 1, k * (iterK + 2));
25+
}
26+
27+
return ret;
28+
};
29+
30+
var reverse = function(s, start, end) {
31+
var ret = "";
32+
if(end >= s.length)
33+
end = s.length - 1;
34+
35+
while(start <= end) {
36+
ret += s.charAt(end);
37+
end--;
38+
}
39+
return ret;
40+
}
41+
42+
var main = function(){
43+
console.log(reverseStr("abcdefg", 2));
44+
console.log(reverseStr("abcdefg", 3));
45+
console.log(reverseStr("abcdefg", 1));
46+
console.log(reverseStr("abcdefg", 0));
47+
}
48+
49+
module.exports.main = main

0 commit comments

Comments
 (0)