Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2.
Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.
思路:最长有效的括号,可以看做能够匹配的最长扩展,只有当右括号匹配左括号时才是有效的,因此我们需要计算每个左括号被右括号匹配时可能得到的最长序列;
- int longestValidParentheses(string s) {
- int last = -1;
- int max_len = 0;
- stack<int> st;
- int size = s.size();
- if(size == 0) return 0;
- int index = 0;
- while(!s.empty() || index < size) {
- if(s.at(index) == '(') {
- st.push(index); // 记录待匹配的左括号下标
- } else if (s.at(index) == ')') {
- if(!st.empty()) {
- st.pop();
- if(!st.empty()) max_len = max(max_len,index-st.top()); //分两种情况讨论,1) 栈中有左括号
- else max_len = max(max_len,index-last); 2)栈中无左括号
- } else {
- last = index; //记录未能匹配的右括号下标,之后重新开始匹配
- }
- }
- index++;
- if(index == size) break;
- }
- return max_len;
- }

浙公网安备 33010602011771号