<leetcode c++>1111. 有效括号的嵌套深度

四月打卡第一天

1111.有效括号的嵌套深度

来源:力扣(LeetCode)

 

  这个题目理解题意的关键点是将字符串分成两个字序列(字符位置可以不相邻),而非字串(字符位置必须相邻)。也就是这题需要我们找到两个有效序列,使它们的嵌套深度相差最小,因为总的嵌套深度一定,若|depth(A)-depth(B)|最小,有max( depth(A), depth(B) ) 最小。

  我就想到了记录当前最大嵌套深度和当前嵌套深度,并且保证分配给B的序列嵌套深度一定不大于最大嵌套深度的一半。c++代码如下:

class Solution {
public:
    vector<int> maxDepthAfterSplit(string seq) {
        int n=seq.length();
        vector<int> ans(n,0);
        stack<int> index;
        int max_depth=0;
        int cur_depth=0;
        
        for(int i=0;i<n;i++)
        {
            if(seq[i]=='('){
                cur_depth++;
                max_depth=max(max_depth,cur_depth);
                index.push(i);
            }
            if(seq[i]==')'){
                if(cur_depth>(max_depth+1)/2){
                    ans[i]=1;
                    ans[index.top()]=1;
                }
                cur_depth--;
                index.pop();
            }
        }
        return ans;
    }
};

  但是在看完题解之后,我才知道😳原来还可以有这么简单的方法,左括号按奇偶分配给A、B就可以了!

class Solution {
public:
    vector<int> maxDepthAfterSplit(string seq) {
        int n=seq.length();
        vector<int> ans(n,0);
        for(int i=0;i<n;i++){
            ans[i]= seq[i]=='('? i & 1 : ((i + 1) & 1);
        }
        return ans;
    }
};

执行用时 :4 ms, 在所有 C++ 提交中击败了88.16%的用户

内存消耗 :7.3 MB, 在所有 C++ 提交中击败了100.00%的用户

 

posted @ 2020-04-01 10:21  鳄鱼四驱车  阅读(468)  评论(0)    收藏  举报