|
| 1 | +import com.sun.org.apache.xalan.internal.xsltc.compiler.util.StringStack; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | +import java.util.Stack; |
| 6 | + |
| 7 | +/** |
| 8 | + * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. |
| 9 | + * |
| 10 | + * An input string is valid if: |
| 11 | + * |
| 12 | + * Open brackets must be closed by the same type of brackets. |
| 13 | + * Open brackets must be closed in the correct order. |
| 14 | + * Note that an empty string is also considered valid. |
| 15 | + */ |
| 16 | +public class ValidParentheses { |
| 17 | + |
| 18 | + public static void main(String[] args){ |
| 19 | + String s1 = "{{({})}}"; |
| 20 | + String s2 = "{([)]}"; |
| 21 | + System.out.println("String s1 is valid = " + isValid(s1)); |
| 22 | + System.out.println("String s2 is valid = " + isValid(s2)); |
| 23 | + } |
| 24 | + |
| 25 | + private static boolean isValid(String s) { |
| 26 | + Stack<Character> openingCharsStack = new StringStack(); |
| 27 | + Map<Character, Character> matchingParentheses = new HashMap(); |
| 28 | + matchingParentheses.put('{', '}'); |
| 29 | + matchingParentheses.put('(', ')'); |
| 30 | + matchingParentheses.put('[', ']'); |
| 31 | + for(char c : s.toCharArray()){ |
| 32 | + if(matchingParentheses.containsKey(c)) { |
| 33 | + openingCharsStack.push(c); |
| 34 | + } |
| 35 | + else if((openingCharsStack.isEmpty() && matchingParentheses.containsValue(c)) |
| 36 | + || (!openingCharsStack.isEmpty() && matchingParentheses.get(openingCharsStack.pop()) != c)) { |
| 37 | + return false; |
| 38 | + } |
| 39 | + } |
| 40 | + return true; |
| 41 | + } |
| 42 | +} |
0 commit comments