zoukankan      html  css  js  c++  java
  • [LeetCode]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 class Solution {
     2 public:
     3     int longestValidParentheses(string s) {
     4         vector<int> cache;
     5         int last = -1; //最后一个')'
     6         int max_len = 0;
     7         for (int i = 0; i < s.size(); ++i) {
     8             if (s[i] == ')') {
     9                 if (cache.empty()) {
    10                     last = i;
    11                 } else {
    12                     cache.pop_back();
    13                     if (cache.empty()) {
    14                         max_len = max(max_len, i - last);
    15                     } else {
    16                         max_len = max(max_len, i - cache.back());
    17                     }
    18                 }
    19             } else {
    20                 cache.push_back(i);
    21             }
    22         }
    23         return max_len;
    24     }
    25 };
  • 相关阅读:
    react 滑动删除组件
    004-Java进制转换
    003-JavaString数据类型
    002-Java数据类型
    001-Java命名规范
    【leetcode】804
    【MySQL】基本语句
    【python】
    hiveSql常见错误记录
    【数据库】-基本特性
  • 原文地址:https://www.cnblogs.com/skycore/p/4972428.html
Copyright © 2011-2022 走看看