Guest User

Untitled

a guest
Jan 8th, 2018
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.07 KB | None | 0 0
  1. import java.util.ArrayDeque;
  2. import java.util.Deque;
  3. import java.util.Scanner;
  4.  
  5. import static java.lang.System.in;
  6. import static java.lang.System.out;
  7.  
  8. /*
  9.  *
  10.  *
  11. Use a stack to check parentheses, balanced and nesting
  12.  *  The parentheses are: (), [] and {}
  13.  *
  14.  *  See:
  15.  *  - UseAStack
  16.  *
  17.  */
  18.  
  19. public class Ex3CheckParen {
  20.  
  21.  
  22.     public static void main(String[] args) {
  23.         new Ex3CheckParen().program();
  24.     }
  25.  
  26.  
  27.     void program() {
  28.         // All should be true
  29.         out.println(checkParentheses("()"));
  30.  
  31.         out.println(checkParentheses("(()())"));
  32.  
  33.         out.println(!checkParentheses("(()))")); // Unbalanced
  34.  
  35.         out.println(!checkParentheses("((())")); // Unbalanced
  36.  
  37.  
  38.         out.println(checkParentheses("({})"));
  39.  
  40.         out.println(!checkParentheses("({)}"));  // Bad nesting
  41.  
  42.         out.println(checkParentheses("({} [()] ({}))"));
  43.  
  44.         out.println(!checkParentheses("({} [() ({)})"));  // Unbalanced and bad nesting
  45.  
  46.     }
  47.  
  48.  
  49.     // This is interesting because have to return, but what if no match?!?
  50.  
  51.     boolean checkParentheses(String str) {
  52.         Deque<Character> stack = new ArrayDeque<>();
  53.  
  54.         String k = "({[";
  55.         String s = ")]}";
  56.         for (int i = 0; i < str.length(); i++) {
  57.             if (k.contains(String.valueOf(str.charAt(i)))) {
  58.                 stack.push(str.charAt(i));
  59.             } else if (s.contains(String.valueOf(str.charAt(i)))) {
  60.  
  61.                 if (matching(stack.peek()) == str.charAt(i)) {
  62.                     return true;
  63.                 }
  64.             } else{
  65.                 return false;
  66.             }
  67.         }
  68.         return false;
  69.     }
  70.  
  71.  
  72.  
  73.     char matching(char ch) {
  74.         //char c =  must initialize but to what?!
  75.  
  76.         switch (ch) {
  77.             case ')':
  78.                 return '('; // c = '('
  79.  
  80.             case ']':
  81.                 return '[';
  82.  
  83.             case '}':
  84.                 return '{';
  85.  
  86.             default:
  87.                 // return c;
  88.  
  89.                 throw new IllegalArgumentException("No match found");
  90.         }
  91.     }
  92. }
Add Comment
Please, Sign In to add comment