I'm trying to replace all brackets with their opposite facing bracket as my take of solving the coding challenge on Hackerrank.com found here.
I think have a solution to the challenge, but I can't seem to get the replace all function to work properly on my function. I've tried using Pattern.quote(String)
as well as the escape backslashes, but for some reason my brackets are not being replaced.
public class Solution {
public static boolean isBalanced(String expression) {
if(expression.length() %2 != 0) {
return false;
}
else {
int middle = expression.length() /2;
String open = expression.substring(0,middle);
String close = expression.substring(middle);
close.replaceAll("\\)", "\\(");
close.replaceAll(Pattern.quote("}"),"{");
close.replaceAll(Pattern.quote("]"), "[");
new StringBuilder(close).reverse().toString();
if(close.equals(open))
return true;
else
return false;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for (int a0 = 0; a0 < t; a0++) {
String expression = in.next();
System.out.println( (isBalanced(expression)) ? "YES" : "NO" );
}
}
}
Edit: I tested the code with a print statement after the line new StringBuilder(close).reverse().toString();
Input:
3
{[()]}
{[(])}
{{[[(())]]}
Output:
)]}
NO
])}
NO
))]]}}
NO