Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayDeque;
- import java.util.Deque;
- import java.util.Scanner;
- import static java.lang.System.in;
- import static java.lang.System.out;
- /*
- *
- *
- Use a stack to check parentheses, balanced and nesting
- * The parentheses are: (), [] and {}
- *
- * See:
- * - UseAStack
- *
- */
- public class Ex3CheckParen {
- public static void main(String[] args) {
- new Ex3CheckParen().program();
- }
- void program() {
- // All should be true
- out.println(checkParentheses("()"));
- out.println(checkParentheses("(()())"));
- out.println(!checkParentheses("(()))")); // Unbalanced
- out.println(!checkParentheses("((())")); // Unbalanced
- out.println(checkParentheses("({})"));
- out.println(!checkParentheses("({)}")); // Bad nesting
- out.println(checkParentheses("({} [()] ({}))"));
- out.println(!checkParentheses("({} [() ({)})")); // Unbalanced and bad nesting
- }
- // This is interesting because have to return, but what if no match?!?
- boolean checkParentheses(String str) {
- Deque<Character> stack = new ArrayDeque<>();
- String k = "({[";
- String s = ")]}";
- for (int i = 0; i < str.length(); i++) {
- if (k.contains(String.valueOf(str.charAt(i)))) {
- stack.push(str.charAt(i));
- } else if (s.contains(String.valueOf(str.charAt(i)))) {
- if (matching(stack.peek()) == str.charAt(i)) {
- return true;
- }
- } else{
- return false;
- }
- }
- return false;
- }
- char matching(char ch) {
- //char c = must initialize but to what?!
- switch (ch) {
- case ')':
- return '('; // c = '('
- case ']':
- return '[';
- case '}':
- return '{';
- default:
- // return c;
- throw new IllegalArgumentException("No match found");
- }
- }
- }
Add Comment
Please, Sign In to add comment