We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}" Output: true
Example 3:
Input: "(]" Output: false
Example 4:
Input: "([)]" Output: false
Example 5:
Input: "{[]}" Output: true
题目要求匹配括号,很简单。C++解法如下:
class Solution { public: bool isValid(string s) { stack<char> help; for (int i = 0; i < s.size(); ++i) { char c = s[i]; if (c == '(' || c == '[' || c == '{') help.push(c); else { if (help.empty()) return false; char old = help.top(); help.pop(); if (c == ')' && old != '(') return false; else if (c == ']' && old != '[') return false; else if (c == '}' && old != '{') return false; } } if (!help.empty()) return false; else return true; } };
Java的栈(容器)是不能存储基本类型的,只能做一个标记:
class Solution { public boolean isValid(String s) { if (s.isEmpty()) { return true; } Stack<Integer> help = new Stack(); int i = 0; for (; i < s.length(); ++i) { if (s.charAt(i) == '(') help.push(1); else if (s.charAt(i) == '[') help.push(2); else if (s.charAt(i) == '{') help.push(3); else { char now = s.charAt(i); if (help.empty()) return false; int old = help.pop(); if (now == ')' && old != 1) return false; else if (now == ']' && old != 2) return false; else if (now == '}' && old != 3) return false; } } if (help.empty()) return true; else return false; } }
参考资料: LeetCode原题
The text was updated successfully, but these errors were encountered:
No branches or pull requests
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Note that an empty string is also considered valid.
Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
题目要求匹配括号,很简单。C++解法如下:
Java的栈(容器)是不能存储基本类型的,只能做一个标记:
参考资料:
LeetCode原题
The text was updated successfully, but these errors were encountered: