Valid Parentheses

描述

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

分析

代码

  1. // Valid Parentheses
  2. // 时间复杂度O(n),空间复杂度O(n)
  3. public class Solution {
  4. public boolean isValid(String s) {
  5. final String left = "([{";
  6. final String right = ")]}";
  7. Stack<Character> stk = new Stack<>();
  8. for (int i = 0; i < s.length(); ++i) {
  9. final char c = s.charAt(i);
  10. if (left.indexOf(c) != -1) {
  11. stk.push (c);
  12. } else {
  13. if (!stk.isEmpty() &&
  14. stk.peek() == left.charAt(right.indexOf(c)))
  15. stk.pop ();
  16. else
  17. return false;
  18. }
  19. }
  20. return stk.empty();
  21. }
  22. }

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/stack-and-queue/stack/valid-parentheses.html