题解 | #最长的括号子串#

最长的括号子串

https://www.nowcoder.com/practice/45fd68024a4c4e97a8d6c45fc61dc6ad?tpId=295&tqId=715&ru=%2Fpractice%2F28970c15befb4ff3a264189087b99ad4&qru=%2Fta%2Fformat-top101%2Fquestion-ranking&sourceUrl=%2Fexam%2Foj

唉,心情全无。

难受啊。

class Solution {
public:
    /**
     * 
     * @param s string字符串 
     * @return int整型
     */
    int longestValidParentheses(string s) {
      int res = 0;
      //  连续括号结束的位置(最后一个非连续括号)
      int start = -1;
      std::stack<int> st;
      
      for (int i = 0; i < s.size(); ++i) {
        if (s[i] == '(') {
          st.push(i);
        } else {
          if (st.empty()) {
            start = i;
          } else {
            st.pop();
            if (!st.empty()) {
              res = std::max(res, i - st.top());
            } else {
              res = std::max(res, i - start);
            }
          }
        }
      }
      
      return res;
    }
};

动态规划转移有点费劲

class Solution {
public:
    /**
     * 
     * @param s string字符串 
     * @return int整型
     */
    int longestValidParentheses(string s) {
      if (s.empty()) {
        return 0;
      }
      //  dp[i] 代表以下表i为结尾的字符串的最长括号子串
      std::vector<int> dp(s.size(), 0);
      int res = 0;
      
      //  只需要查看右括号,以左括号结尾的字符串一定不会是子串
      for (int i = 1; i < s.size(); ++i) {
        if (s[i] == ')') {
          if (s[i - 1] == '(') {
            dp[i] = (i > 1 ? dp[i - 2] : 0) + 2;
            //  找到与之匹配的左括号
          } else if (i - dp[i - 1] > 0 && s[i - dp[i - 1] - 1] == '(') {
            dp[i] = (i - dp[i - 1] > 1 ? dp[i - dp[i - 1] - 2] : 0) + dp[i - 1] + 2;
          }
        }
        res = std::max(res, dp[i]);
      }
      
      return res;
    }
};
全部评论

相关推荐

不愿透露姓名的神秘牛友
今天 16:32
FieldMatching:看你已读不回是有什么顾虑吗?
点赞 评论 收藏
分享
qq乃乃好喝到咩噗茶:院校后面加上211标签,放大加粗,招呼语也写上211
点赞 评论 收藏
分享
那一天的Java_Java起来:他本来公司就是做这个的,不就是正常的游戏客户端和服务器开发,软硬件联动,有啥恶心不恶心的,提前告诉你就是怕你接受不了,接受不了就没必要再往后走流程浪费时间,虽然这公司是一坨。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务