1111. Maximum Nesting Depth of Two Valid Parentheses Strings(Leetcode每日一题-2020.04.01)

Problem

A string is a valid parentheses string (denoted VPS) if and only if it consists of “(” and “)” characters only, and:

  • It is the empty string, or
  • It can be written as AB (A concatenated with B), where A and B are VPS’s, or
  • It can be written as (A), where A is a VPS.

We can similarly define the nesting depth depth(S) of any VPS S as follows:

  • depth("") = 0
  • depth(A + B) = max(depth(A), depth(B)), where A and B are VPS’s
  • depth("(" + A + “)”) = 1 + depth(A), where A is a VPS.

For example, “”, “()()”, and “()(()())” are VPS’s (with nesting depths 0, 1, and 2), and “)(” and “(()” are not VPS’s.

Given a VPS seq, split it into two disjoint subsequences A and B, such that A and B are VPS’s (and A.length + B.length = seq.length).

Now choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value.

Return an answer array (of length seq.length) that encodes such a choice of A and B: answer[i] = 0 if seq[i] is part of A, else answer[i] = 1. Note that even though multiple answers may exist, you may return any of them.

Example1

Input: seq = “(()())”
Output: [0,1,1,1,1,0]

Example2

Input: seq = “()(())()”
Output: [0,0,0,1,1,0,1,1]

Solution

字都认得,就是不知道题啥意思。看了解析才会。

思路:

  • 根据 depth(A + B) = max(depth(A), depth(B)) 这个定义,整体的「嵌套深度」取决于子序列的「嵌套深度」的最大者;
  • 要使得 max(depth(A), depth(B)) 的可能取值最小,分析示例的时候提到这很像一棵二叉树,要使得二叉树的深度最小,那么就需要该二叉树平衡,一个可行的做法是:把栈中连续出现的左括号 ( 根据奇偶性分到不同的组,右括号随与之匹配左括号的组号;
  • 如果出现 () 这种子序列,即左括号后面连着出现了右括号,其实分在那一组都是没有关系的,因为它的存在不会使得「嵌套深度」更深。

在这里插入图片描述

把深度为1和3的分给A,深度为2的分给B。

class Solution {
public:
   vector<int> maxDepthAfterSplit(string seq) {
        int d = 0;
        vector<int> ans;
        for (char& c : seq)
            if (c == '(') {
                ++d;
                ans.push_back(d % 2);
                
            }
            else {
                
                ans.push_back(d % 2);
                --d;//注意
            }
        return ans;
    }

};

Ref

https://leetcode-cn.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/solution/qian-tao-shen-du-wan-cheng-gua-hao-pi-pei-wen-ti-s/

发布了547 篇原创文章 · 获赞 217 · 访问量 56万+

猜你喜欢

转载自blog.csdn.net/sjt091110317/article/details/105254533