forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverseStringII.java
46 lines (42 loc) · 1.16 KB
/
ReverseStringII.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.leetcode.strings;
/**
* Level: Easy
* Problem: https://leetcode.com/problems/reverse-string-ii/
*
* @author rampatra
* @since 2019-04-20
*/
public class ReverseStringII {
/**
* Time complexity: O(n)
* where,
* n = no. of characters in string
* <p>
* Runtime: <a href="https://leetcode.com/submissions/detail/223715011/">0 ms</a>.
*
* @param str
* @param k
* @return
*/
public static String reverseStr(String str, int k) {
char[] chars = str.toCharArray();
int len = str.length();
for (int i = 0; i < len; i += 2 * k) {
reverse(chars, i, Math.min(len, i + k));
}
return new String(chars);
}
private static void reverse(char[] chars, int start, int end) {
char temp;
for (int i = start, j = end - 1; i < j; i++, j--) {
temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
}
public static void main(String[] args) {
System.out.println(reverseStr("abcdefg", 2));
System.out.println(reverseStr("abcdef", 2));
System.out.println(reverseStr("abcde", 2));
}
}