Stack - simple enough that is data structure of stack
the following code is java implementation of using stack to check the code syntax are properly closed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | import java.util.*; class SyntaxTester { private HashMap<String, String> mapping; public SyntaxTester() { mapping = new HashMap<String, String>(); mapping.put("(", ")"); mapping.put("[", "]"); mapping.put("{", "}"); } public void check(String input) { Stack<String> stack = new Stack<String>(); for (int i = 0 ; i < input.length() ; i++ ) { String currentString = input.substring(i, i+ 1) ; //opener if ( mapping.keySet().contains(currentString) ) { stack.add(currentString); } //closer else if (mapping.containsValue(currentString)) { //get last stack element String lastElement = stack.peek(); if (mapping.get(lastElement).equals(currentString) ) { stack.pop(); } } } if (stack.empty()) { System.out.println("input : " + input + " is valid."); } else { System.out.println("input : " + input + " is not valid."); } } } class HashMapDemo { public static void main(String[] args) { String input = "{[]()}"; SyntaxTester tester = new SyntaxTester(); if (args.length > 0) { tester.check(args[0]); } else { tester.check(input); } } } |
沒有留言:
張貼留言