Simple program to validate parenthesis in a string. e.g. "(12(ab(dkc)))" is valid but "(12(ab)(dkc)))" is not
The simple solution is to use stack to push the "(" character and pop the same when you have ")"
The simple solution is to use stack to push the "(" character and pop the same when you have ")"
import java.util.Stack;
public class StringValidation {
public Boolean isValid(String str) {
Boolean isValid = true;
Stack stack = new Stack<>();
char[] chars = str.toCharArray();
for (char achar : chars) {
if (achar == '(') {
stack.push(achar);
}
if (achar == ')') {
if (stack.isEmpty()) return false;
stack.pop();
}
}
if (!stack.isEmpty()) return false;
return isValid;
}
public static void main(String [] args) {
String str1 = "(12(ab(dkc)))";
String str2 = "(12(a)b(dkc)))";
StringValidation ex = new StringValidation();
System.out.println("str1: " + ex.isValid(str1));
System.out.println("str2: " + ex.isValid(str2));
}
}
No comments:
Post a Comment