Skip to content

Commit 933bc38

Browse files
committed
Reverse String II done
1 parent 1853108 commit 933bc38

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed

src/main/java/com/leetcode/strings/RansomNote.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -36,4 +36,4 @@ public static void main(String[] args) {
3636
System.out.println(canConstruct("ab", "ab"));
3737
System.out.println(canConstruct("aab", "ab"));
3838
}
39-
}
39+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.leetcode.strings;
2+
3+
/**
4+
* Problem: https://leetcode.com/problems/reverse-string-ii/
5+
*
6+
* @author rampatra
7+
* @since 2019-04-20
8+
*/
9+
public class ReverseStringII {
10+
11+
/**
12+
* Time complexity: O(n)
13+
* where,
14+
* n = no. of characters in string
15+
* <p>
16+
* Runtime: <a href="https://leetcode.com/submissions/detail/223714484/">0 ms</a>.
17+
*
18+
* @param str
19+
* @param k
20+
* @return
21+
*/
22+
public static String reverseStr(String str, int k) {
23+
char[] chars = str.toCharArray();
24+
int len = str.length();
25+
int i = 0;
26+
while (i < len) {
27+
if (len - i + 1 >= 2 * k) {
28+
reverse(chars, i, i + k);
29+
} else {
30+
reverse(chars, i, Math.min(len, i + k));
31+
}
32+
i += 2 * k;
33+
}
34+
return new String(chars);
35+
}
36+
37+
private static void reverse(char[] chars, int start, int end) {
38+
char temp;
39+
for (int i = start, j = end - 1; i < j; i++, j--) {
40+
temp = chars[i];
41+
chars[i] = chars[j];
42+
chars[j] = temp;
43+
}
44+
}
45+
46+
public static void main(String[] args) {
47+
System.out.println(reverseStr("abcdefg", 2));
48+
System.out.println(reverseStr("abcdef", 2));
49+
System.out.println(reverseStr("abcde", 2));
50+
}
51+
}

0 commit comments

Comments
 (0)