• [leetcode]Longest Valid Parentheses


    第二刷:

    首先,此题可以用O(n)的空间做,就是第一遍标识所有匹配的位置,第二遍找最长连续的匹配就行了。那么改善一点就是记录上一个不匹配的位置就行了,上一个不匹配的位置有两种,一种是多余的')',这个用一个变量记录;另一个是'(',这个用栈记录。

    class Solution {
    public:
        int longestValidParentheses(string s) {
            stack<int> stk; // this stack stores all unmatched '(' positions
            int lastRight = -1; // last unmatched ')' position
            int longest = 0;
            for (int i = 0; i < s.size(); i++) {
                if (s[i] == '(') {
                    stk.push(i);
                } else { // ')'
                    if (!stk.empty()) {
                        stk.pop();
                        if (!stk.empty()) {
                            longest = max(longest, i - stk.top()); 
                        } else {
                            longest = max(longest, i - lastRight); 
                        }
                    } else { // no match
                        lastRight = i;
                    }
                }
            }
            return longest;
        }
    };

     第一刷:

    此题有点难度。知道了:1.括号匹配的题目可以用stack;2.stack里面可以放括号的index;3.用一个last标记上一个失匹配的')‘,相当于重置;参考:http://discuss.leetcode.com/questions/212/longest-valid-parentheses

    http://www.cnblogs.com/remlostime/archive/2012/11/25/2787878.html

    #include <string>
    #include <stack>
    using namespace std;
    class Solution {
    public:
        // (()())
        // (()
    	// ()((()
        int longestValidParentheses(string s) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
        	int max_len = 0;
    		int last = -1;
            stack<int> lefts;
    		for (int i = 0; i < s.size(); i++) {
    			if (s[i] == '(')
        		{
    				lefts.push(i);
    			}
                else //if (s[i] == ')' )
    			{
    				// no matching '('
    				if (lefts.empty()) {
    					last = i;
    				}
    				else
    				{
    					lefts.pop();
    					if (lefts.empty())
    					{
    						int len = i - last;
                            if (len > max_len) max_len = len; 
    						
    					}
    					else
    					{
    						int len = i - lefts.top();
    						if (len > max_len) max_len = len; 
    					}
    				}
    			} 
    		}
    		return max_len;
        }
    };
      
    

      

  • 相关阅读:
    洛谷 P1141 01迷宫
    洛谷 p1443
    setw
    Fliptile
    追牛
    Dungeon Master
    vim的一些基本操作
    洛谷 p1309 瑞士轮
    洛谷 p1090 合并果子
    selenium2 WebDriver 在asp.net项目中的应用
  • 原文地址:https://www.cnblogs.com/lautsie/p/3234879.html
Copyright © 2020-2023  润新知