20. Valid Parentheses
错误解法:
"[])"就会报错,没考虑到出现')'、']'、'}'时,stack为空的情况,这种情况也无法匹配
class Solution { public:bool isValid(string s) {if(s.empty())return false;stack<char> st;st.push(s[0]);for(int i = 1;i < s.size();i++){if(s[i] == '(' || s[i] == '[' || s[i] == '{')st.push(s[i]);else if(s[i] == ')'){if(st.top() == '(')st.pop();elsereturn false;}else if(s[i] == ']'){if(st.top() == '[')st.pop();elsereturn false;}else if(s[i] == '}'){if(st.top() == '{')st.pop();elsereturn false;}}return st.empty() ? true : false;} };
正确解法:
class Solution { public:bool isValid(string s) {int length = s.size();if(length < 0)return false;stack<char> result;for(int i = 0;i < length;i++){if(s[i] == '(' || s[i] == '[' || s[i] == '{')result.push(s[i]);else{if(result.empty())return false;if(s[i] == ')' && result.top() != '(')return false;if(s[i] == ']' && result.top() != '[')return false;if(s[i] == '}' && result.top() != '{')return false;result.pop();}}return result.empty();} };
32. Longest Valid Parentheses
https://www.cnblogs.com/grandyang/p/4424731.html
这个题求的是最长的连续匹配正确的符号。
匹配错误只可能是右括号')'存在时,堆中没有左括号'('进行匹配。start用来继续这个连续匹配的开始位置,只有在匹配错误的情况下,这个start才更新。
如果匹配成功后,堆中没有左括号'(',则说明从start到当前都是匹配正确了的;
注意必须用i - position.top(),可能出现这种情况'(()()',如果你使用i - position弹出的那个位置,你永远只可能获得长度为2的,不可能获得连续的长度。
class Solution { public:int longestValidParentheses(string s) {int start = 0,res = 0;stack<int> position;for(int i = 0;i < s.size();i++){if(s[i] == '(')position.push(i);else if(s[i] == ')'){if(position.empty())start = i + 1;else{position.pop();res = position.empty() ? max(res,i - start + 1) : max(res,i - position.top());}}}return res;} };
自己写的一个版本,更容易理解:
class Solution { public:int longestValidParentheses(string s) {stack<int> sta;int res = 0;int left = -1;for(int i = 0;i < s.size();i++){if(s[i] == '(')sta.push(i);else{if(sta.empty())left = i;else{int index = sta.top();sta.pop();if(sta.empty())res = max(res,i - left);elseres = max(res,i - sta.top());}}}return res;} };
301. Remove Invalid Parentheses
这个题是求删除后所有合法的,并且要求删除次数必须最少。
这个题与前面两个题稍稍有点不同,这个题需要用bfs的方式,把每个位置的字符删除加入队列判断是否合法,一旦有合法的就不再进行删除操作,而是把队列中剩下的进行判断是否合法就行了。
使用了visited数组,这样防止了搜索的重复计算
class Solution { public:vector<string> removeInvalidParentheses(string s) {vector<string> res;unordered_set<string> visited;visited.insert(s);queue<string> q;q.push(s);bool finished = false;while(!q.empty()){string tmp = q.front();q.pop();if(isValid(tmp)){res.push_back(tmp);finished = true;}if(finished)continue;for(int i = 0;i < tmp.size();i++){if(tmp[i] != '(' && tmp[i] != ')')continue;string t = tmp.substr(0,i) + tmp.substr(i+1);if(!visited.count(t)){visited.insert(t);q.push(t);}}}return res;}bool isValid(string s){int count = 0;for(int i = 0;i < s.size();i++){if(s[i] != '(' && s[i] != ')')continue;else if(s[i] == '(')count++;else{if(count <= 0)return false;elsecount--;}}return count == 0;} };