Last active
May 10, 2020 12:26
-
-
Save HoussemNasri/f433ba927a7560c8d98f22b42f96dc72 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example; | |
import java.util.Stack; | |
public class Main { | |
public static final char OPENING_PARENTHESES = '('; | |
public static final char CLOSING_PARENTHESES = ')'; | |
public static void swap(char[] string, int i, int j) { | |
char temp = string[i]; | |
string[i] = string[j]; | |
string[j] = temp; | |
} | |
/** | |
* @param leftParentheses Index of the left parentheses in the string | |
* @param rightParentheses Index of the right parentheses in the string | |
*/ | |
public static void reverseStringInsideParentheses(char[] string, int leftParentheses, int rightParentheses) { | |
int left = leftParentheses + 1; | |
int right = rightParentheses - 1; | |
while (left < right) { | |
// Swap | |
swap(string, left, right); | |
left++; | |
right--; | |
} | |
} | |
// The actual solution | |
public static String solve(String string) { | |
char[] solution = string.toCharArray(); | |
int n = solution.length; | |
// Store openings parentheses indexes | |
Stack<Integer> openings = new Stack<>(); | |
for (int i = 0; i < n; i++) { | |
char currentChar = solution[i]; | |
if (currentChar == OPENING_PARENTHESES) { | |
openings.push(i); | |
} | |
if (currentChar == CLOSING_PARENTHESES) { | |
if (openings.isEmpty()) | |
throw new IllegalStateException("Unbalanced parentheses !!!"); | |
int leftPar = openings.pop(); | |
int rightPar = i; | |
reverseStringInsideParentheses(solution, leftPar, rightPar); | |
} | |
} | |
// remove all parentheses in the string | |
return String.valueOf(solution).replaceAll("[()]", ""); | |
} | |
public static void main(String[] args) { | |
String TEST_CASE_1 = "I(love)you"; //Ievolyou | |
String TEST_CASE_2 = "I(love(you))too"; //Iyouevoltoo | |
String TEST_CASE_3 = "Java Pro(gr(am(me))r)s"; //Java Proramemrgs | |
String TEST_CASE_4 = "(abcd)"; //dcba | |
String TEST_CASE_5 = "(ed(et(oc))el)"; //leetcode | |
System.out.println(solve(TEST_CASE_1)); | |
System.out.println(solve(TEST_CASE_2)); | |
System.out.println(solve(TEST_CASE_3)); | |
System.out.println(solve(TEST_CASE_4)); | |
System.out.println(solve(TEST_CASE_5)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment