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.
这一题是典型的使用压栈的方式解决的问题,
解题思路:因为这是不同距离之间的比较,用栈解决这样的问题,我们对字符串S中的每一个字符C,如果C不是右括号,就压入栈stack中。
如果C是右括号,判断stack是不是空的,空则说明没有左括号,直接返回not valid,非空就取出栈顶的字符pre来对比,如果是匹配
的,就弹出栈顶的字符,继续取S中的下一个字符;如果不匹配,说明不是valid的,直接返回。当我们遍历了一次字符串S后,注意
这里还有一种情况,就是stack中还有残留的字符没有得到匹配,即此时stack不是空的,这时说明S不是valid的,因为只要valid,一
定全都可以得到匹配使左括号弹出。
#include<iostream> #include<string> #include<algorithm> #include<stack> using namespace std; int main() { string s = "((((()))[[[]]]]]"; stack<char> temp; int i = 0; bool sign=true; while (i != s.size()) { char a = s[i]; if (a != ')' && (a != ']') && (a != '}')) { temp.push(a); } else { if (temp.size() == 0) { sign = false; break; } char top = temp.top(); temp.pop(); if (((a != ')' && top == '(') || ((a != ']') && top == '[') || (a != '}') && (top == '{'))) { sign = false; break; } } i++; } if (temp.size() == 0) { sign = true; } cout << sign << endl; system("pause"); return 0; }
class Solution { public: bool isValid(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function stack<char> st; for(int i = 0; i < s.size(); i++) if (s[i] == ')' || s[i] == ']' || s[i] == '}') { if (st.empty()) return false; else { char c = st.top(); st.pop(); if ((c == '(' && s[i] != ')') || (c == '[' && s[i] != ']') || (c == '{' && s[i] != '}')) return false; } } else st.push(s[i]); return st.empty(); } };
class Solution { public: bool isValid(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function stack<char> st; for(int i = 0; i < s.size(); i++) if (s[i] == ')' || s[i] == ']' || s[i] == '}') { if (st.empty()) return false; else { char c = st.top(); st.pop(); if ((c == '(' && s[i] != ')') || (c == '[' && s[i] != ']') || (c == '{' && s[i] != '}')) return false; } } else st.push(s[i]); return st.empty(); } };
public class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); for (int i=0; i<s.length(); i++) { char ch = s.charAt(i); if (ch=='(' || ch=='[' || ch=='{') stack.push(ch); if (ch==')' && (stack.empty() || stack.pop()!='(')) return false; if (ch==']' && (stack.empty() || stack.pop()!='[')) return false; if (ch=='}' && (stack.empty() || stack.pop()!='{')) return false; } // for if (!stack.empty()) return false; return true; } }