• leetcode Longest Valid Parentheses


    题目连接

    https://leetcode.com/problems/longest-valid-parentheses/ 

    Longest Valid Parentheses

    Description

    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. 

    记录括号出现的位置,找连续最长的一段。。

    class Solution {
    public:
    	int longestValidParentheses(string s) {
    		if (s.empty()) return 0;
    		int n = s.length();
    		stack<int> st;
    		vector<bool> vis(n + 10);
    		for (int i = 0; i < n; i++) {
    			char &c = s[i];
    			if (c == '(') {
    				st.push(i);
    			} else if (c == ')' && !st.empty()){
    				vis[i] = true;
    				vis[st.top()] = true; st.pop();
    			}
    		}
    		int ans = 0, ret = 0;
    		for (int i = 0; i < n; i++) {
    			if (vis[i]) ++ret;
    			else ret = 0;
    			ans = max(ans, ret);
    		}
    		return ans;
    	}
    };
  • 相关阅读:
    Hibernate Validation注解列表
    Java_Shell多线程
    Lua读写文件
    shell导出和导入redis
    大文件读写
    Java_Hbase优化
    控制语句if
    字典(DICT)
    元组Tuple
    Session 会话
  • 原文地址:https://www.cnblogs.com/GadyPu/p/5040184.html
Copyright © 2020-2023  润新知