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.

思路:最长有效的括号,可以看做能够匹配的最长扩展,只有当右括号匹配左括号时才是有效的,因此我们需要计算每个左括号被右括号匹配时可能得到的最长序列;

  1. int longestValidParentheses(string s) {
  2. int last = -1;
  3. int max_len = 0;
  4. stack<int> st;
  5. int size = s.size();
  6. if(size == 0) return 0;
  7. int index = 0;
  8. while(!s.empty() || index < size) {
  9. if(s.at(index) == '(') {
  10. st.push(index); // 记录待匹配的左括号下标
  11. } else if (s.at(index) == ')') {
  12. if(!st.empty()) {
  13. st.pop();
  14. if(!st.empty()) max_len = max(max_len,index-st.top()); //分两种情况讨论,1) 栈中有左括号
  15. else max_len = max(max_len,index-last);   2)栈中无左括号
  16. } else {
  17. last = index; //记录未能匹配的右括号下标,之后重新开始匹配
  18. }
  19. }
  20. index++;
  21. if(index == size) break;
  22. }
  23. return max_len;
  24. }
posted @ 2014-10-05 10:30  purejade  阅读(88)  评论(0)    收藏  举报