-
Notifications
You must be signed in to change notification settings - Fork 0
/
1190.reverse-substrings-between-each-pair-of-parentheses.java
93 lines (85 loc) · 1.93 KB
/
1190.reverse-substrings-between-each-pair-of-parentheses.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
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
* @lc app=leetcode id=1190 lang=java
*
* [1190] Reverse Substrings Between Each Pair of Parentheses
*
* https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/description/
*
* algorithms
* Medium (59.94%)
* Likes: 278
* Dislikes: 12
* Total Accepted: 14.6K
* Total Submissions: 24.2K
* Testcase Example: '"(abcd)"'
*
* You are given a string s that consists of lower case English letters and
* brackets.
*
* Reverse the strings in each pair of matching parentheses, starting from the
* innermost one.
*
* Your result should not contain any brackets.
*
*
* Example 1:
*
*
* Input: s = "(abcd)"
* Output: "dcba"
*
*
* Example 2:
*
*
* Input: s = "(u(love)i)"
* Output: "iloveu"
* Explanation: The substring "love" is reversed first, then the whole string
* is reversed.
*
*
* Example 3:
*
*
* Input: s = "(ed(et(oc))el)"
* Output: "leetcode"
* Explanation: First, we reverse the substring "oc", then "etco", and finally,
* the whole string.
*
*
* Example 4:
*
*
* Input: s = "a(bcdefghijkl(mno)p)q"
* Output: "apmnolkjihgfedcbq"
*
*
*
* Constraints:
*
*
* 0 <= s.length <= 2000
* s only contains lower case English characters and parentheses.
* It's guaranteed that all parentheses are balanced.
*
*
*/
// @lc code=start
// 1190. Reverse Substrings Between Each Pair of Parentheses
// simulate, when encounter '(', do recursive call.
class Solution {
int i = 0;
public String reverseParentheses(String s) {
StringBuilder sb = new StringBuilder();
while (i < s.length()) {
char c = s.charAt(i++);
if (c == '(') {
String substr = reverseParentheses(s);
sb.append((new StringBuilder(substr)).reverse());
} else if (c == ')') break;
else sb.append(c);
}
return sb.toString();
}
}
// @lc code=end