You are viewing a single comment's thread. Return to all comments →
import java.util.Scanner; import java.util.Stack;
public class JavaStackParanthesis { public static void main(String[] argh) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String input = sc.next(); System.out.println(validate(input)); } sc.close(); }
private static boolean validate(String str) { boolean isValid = false; if (str == null || str.length() % 2 != 0) { return false; } Stack<Character> stack = new Stack<>(); char[] chr = str.toCharArray(); for (char ch : chr) { if (ch == '{' || ch == '(' || ch == '[') { stack.push(ch); } else { if (!stack.isEmpty()) { char popCh = stack.pop(); if (ch == '}') { if (popCh == '{') { continue; } break; } else if (ch == ']') { if (popCh == '[') { continue; } break; } else if (ch == ')') { if (popCh == '(') { continue; } break; } } else { return false; } } } if (stack.isEmpty()) { isValid = true; } return isValid; }
}
Seems like cookies are disabled on this browser, please enable them to open this website
Java Stack
You are viewing a single comment's thread. Return to all comments →
import java.util.Scanner; import java.util.Stack;
public class JavaStackParanthesis { public static void main(String[] argh) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String input = sc.next(); System.out.println(validate(input)); } sc.close(); }
}