Java Balanced Expressions Check | Code Factory

public class CheckStringPattern {
static int i = 0;
static char openC = '{', closeC = '}', openR = '[', closeR = ']', openB = '(', closeB = ')';

public static void main(String args[]) {
System.out.println("CheckStringPattern.main()");
String str = "({}()[[]][[[]]]({({{}()})}))";
char array[] = new char[str.length()];

char ch[] = str.toCharArray();
for(char c : ch) {
if(c == openC || c == openR || c == openB) {
array[i] = c;
i = i + 1;
}
if((c == closeC || c == closeR || c == closeB)) {
if(isCloseExist(c, array)) {
i = i - 1;
} else {
i = 1; //set any value in i (other than 0) so it not correct in first IF
break;
}
}
}
if(i == 0) {
System.out.println("Right");
} else {
System.err.println("Wrong");
}
}

private static boolean isCloseExist(char c, char[] array) {
if(i > 0) {
System.out.println(array[i-1] + " : " + c);
if(closeC == c) {
if(array[i-1] != openC) {
return false;
}
} else if(closeR == c) {
if(array[i-1] != openR) {
return false;
}
} else if(closeB == c) {
if(array[i-1] != openB) {
return false;
}
}
return true;
}
return false;
}
}

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Let’s Learn REST to Develop your Application Restfully

Dynamic and Static Libraries, why even bother?

Google Summer of Code FAQ: Most common queries after helping >100 students

Practical DDD — Transforming Theories into Guidelines

Preparing Bricks for Glusterfs

Combine .receive(on: )?

Generators in Python

Creating a dynamic response of an API/Microservice

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Code Factory

Code Factory

More from Medium

Right Garbage Collector in Java simplified

Anonymous/Unnamed code blocks in Java

Multithreading In Java

Java — Overview