|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.LinkedList; |
| 4 | +import java.util.Queue; |
| 5 | +import java.util.Stack; |
| 6 | + |
| 7 | +/** |
| 8 | + * 1190. Reverse Substrings Between Each Pair of Parentheses |
| 9 | + * |
| 10 | + * You are given a string s that consists of lower case English letters and brackets. |
| 11 | + * Reverse the strings in each pair of matching parentheses, starting from the innermost one. |
| 12 | + * Your result should not contain any brackets. |
| 13 | + * |
| 14 | + * Example 1: |
| 15 | + * Input: s = "(abcd)" |
| 16 | + * Output: "dcba" |
| 17 | + * |
| 18 | + * Example 2: |
| 19 | + * Input: s = "(u(love)i)" |
| 20 | + * Output: "iloveu" |
| 21 | + * Explanation: The substring "love" is reversed first, then the whole string is reversed. |
| 22 | + * |
| 23 | + * Example 3: |
| 24 | + * Input: s = "(ed(et(oc))el)" |
| 25 | + * Output: "leetcode" |
| 26 | + * Explanation: First, we reverse the substring "oc", then "etco", and finally, the whole string. |
| 27 | + * |
| 28 | + * Example 4: |
| 29 | + * Input: s = "a(bcdefghijkl(mno)p)q" |
| 30 | + * Output: "apmnolkjihgfedcbq" |
| 31 | + * |
| 32 | + * Constraints: |
| 33 | + * 0 <= s.length <= 2000 |
| 34 | + * s only contains lower case English characters and parentheses. |
| 35 | + * It's guaranteed that all parentheses are balanced. |
| 36 | + * */ |
| 37 | +public class _1190 { |
| 38 | + public static class Solution1 { |
| 39 | + public String reverseParentheses(String s) { |
| 40 | + Stack<Character> stack = new Stack<>(); |
| 41 | + Queue<Character> queue = new LinkedList<>(); |
| 42 | + for (char c : s.toCharArray()) { |
| 43 | + if (c != ')') { |
| 44 | + stack.push(c); |
| 45 | + } else { |
| 46 | + while (!stack.isEmpty() && stack.peek() != '(') { |
| 47 | + queue.offer(stack.pop()); |
| 48 | + } |
| 49 | + if (!stack.isEmpty()) { |
| 50 | + stack.pop();//pop off the open paren |
| 51 | + } |
| 52 | + while (!queue.isEmpty()) { |
| 53 | + stack.push(queue.poll()); |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + StringBuilder sb = new StringBuilder(); |
| 58 | + while (!stack.isEmpty()) { |
| 59 | + sb.append(stack.pop()); |
| 60 | + } |
| 61 | + return sb.reverse().toString(); |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments