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.
用栈会很方便。为了练习vector抽风的没有用栈,很疼……
class Solution { public: bool isValid(string s) { if(s.length() == 0)return 1; vector<char> v; for(int i = 0 ; i < s.length(); i++) { if(is(s[i])) { v.push_back(s[i]); } } if(v.size()%2 ==1)return 0; while(true) { int flag = 0; for(int i = 0 ; i < v.size()&& v.size() > 0; i++) { if(v[i] == ')' || v[i] == ']' || v[i] == '}' ) { if(i == 0)return 0; if(v[i] == ')' &&v[i-1] == '(' ||v[i] == ']' &&v[i-1] == '[' || v[i] == '}' &&v[i-1] == '{' ) { v.erase(v.begin() + i -1 , v.begin() + i +1); break; } else return 0; } if(v.size() == 0)return 1; if(i == v.size() - 1)return 0; } if(v.size() == 0 )break; } return 1; } bool is(char ch) { if(ch == '(' || ch == ')' || ch == '[' || ch ==']' || ch =='{' || ch =='}') return 1; else return 0; } };
posted on 2014-02-27 21:30 pengyu2003 阅读(86) 评论(0) 编辑 收藏 举报