-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseSubstringsBetweenEachPairOfParentheses.java
More file actions
76 lines (70 loc) · 2.5 KB
/
ReverseSubstringsBetweenEachPairOfParentheses.java
File metadata and controls
76 lines (70 loc) · 2.5 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package leetcode;
/**
* ReverseSubstringsBetweenEachPairOfParentheses
* https://leetcode-cn.com/problems/reverse-substrings-between-each-pair-of-parentheses/
* 1190. 反转每对括号间的子串
* https://leetcode-cn.com/problems/reverse-substrings-between-each-pair-of-parentheses/solution/zheng-fan-han-shu-di-gui-by-oshdyr-l1cn/
*
* @author tobin
* @since 2021-05-26
*/
public class ReverseSubstringsBetweenEachPairOfParentheses {
public static void main(String[] args) {
ReverseSubstringsBetweenEachPairOfParentheses sol = new ReverseSubstringsBetweenEachPairOfParentheses();
System.out.println(sol.reverseParentheses("(abcd)"));
System.out.println(sol.reverseParentheses("(u(love)i)"));
System.out.println(sol.reverseParentheses("(ed(et(oc))el)"));
System.out.println(sol.reverseParentheses("a(bcdefghijkl(mno)p)q"));
System.out.println(sol.reverseParentheses("(sugqlinrwj)gasmtbk"));
}
public String reverseParentheses(String s) {
StringBuilder result = new StringBuilder();
// if (s.charAt(0) == '(') { // bug 1: what about "(sugqlinrwj)gasmtbk" ?
// backward(s, 1, result);
// } else {
// forward(s, 0, result);
// }
forward(s, 0, result);
return result.toString();
}
public int backward(String s, int idx, StringBuilder total) {
StringBuilder invSb = new StringBuilder();
int in = idx;
while (in < s.length()) {
char c = s.charAt(in);
if (c == '(') {
StringBuilder tmp = new StringBuilder();
in = forward(s, in + 1, tmp);
invSb.append(tmp.reverse());
} else if (c == ')') {
in++;
break;
} else {
invSb.append(c);
in++;
}
}
total.append(invSb.reverse());
return in;
}
public int forward(String s, int idx, StringBuilder total) {
StringBuilder invSb = new StringBuilder();
int in = idx;
while (in < s.length()) {
char c = s.charAt(in);
if (c == '(') {
StringBuilder tmp = new StringBuilder();
in = backward(s, in + 1, tmp);
invSb.append(tmp);
} else if (c == ')') {
in++;
break;
} else {
invSb.append(c);
in++;
}
}
total.append(invSb);
return in;
}
}