一:解题思路
利用一个辅助栈,当遇到左符号时候,入栈。当遇到右符号时候,与栈顶元素相比是否相等,按照这样的方式将字符串遍历循环下去,看看最后栈是否为空。
二:完整代码示例 (C++版和Java版)
C++
//Time:O(n),Space:O(n) class Solution { public: bool match(char a, char b) { return ((a=='(')&&(b==')')) || ((a=='[')&&(b==']')) || ((a=='{')&&(b=='}')); } bool isValid(string s) { stack<char> stack; if (s.size() == 0) return true; for (int i = 0; i < s.size(); i++) { if ((s[i] == '(') || (s[i] == '[') || (s[i] == '{')) { stack.push(s[i]); } else if ((s[i] == ')') || (s[i] == ']') || (s[i] == '}')) { if ((!stack.empty()) && (match(stack.top(),s[i]))) { stack.pop(); } else { return false; } } } return stack.empty(); } };
Java:
class Solution { public boolean match(char a,char b) { return ((a=='(')&&(b==')'))|| ((a=='[')&&(b==']'))|| ((a=='{')&&(b=='}')); } public boolean isValid(String s) { Stack<Character> stack=new Stack<>(); if (s.length() == 0) return true; for (int i = 0; i < s.length(); i++) { if ((s.charAt(i) == '(') || (s.charAt(i) == '[') || (s.charAt(i) == '{')) { stack.push(s.charAt(i)); } else if ((s.charAt(i) == ')') || (s.charAt(i) == ']') || (s.charAt(i) == '}')) { if ((!stack.isEmpty()) && (match(stack.peek(),s.charAt(i)))) { stack.pop(); } else { return false; } } } return stack.isEmpty(); } };
来源:https://www.cnblogs.com/repinkply/p/12490695.html