Nesting depth of the effective symbol LeetCode # 1111

Title Description

analysis

u1s1 translation of solving the problem really abstract. . . Here is my view of points:

  • String Effective brackets (Valid Parentheses Strings, later abbreviated as VPS) in the front and rear brackets are matched, similar to the situation does not occur "())," ") (" like;
  • The VPS seq, the requirements will be divided into two sub-strings A, B, they also need to be the VPS;
  • VPS depth depth
    • Null character, such as "", depth is 0;
    • Nested, such as "(vps)", the internal depth of vps depth + 1;
      Example: null character ""depth is 0, the ()depth of. 1, (())depth 2;
    • Connection, such as "vpsA vpsB", depth and vpsB the maximum value vpsA;
  • Questions asked seqtwo sub-strings A, B satisfies \ (MAX (depth (A) , depth (B)) \) Minimum

VPS some depends on its depth of nesting depth , and the depth D of some split into two depths, respectively VPS substring DA and DB, there will be \ (D == DA + DB \) (and a doll reason?)
therefore makes \ (MAX (depth (a) , depth (B)) \) minimum, theoretically required \ (the DA = DB = \ FRAC. 1} {2} {D \) , the actual in the case of D does not necessarily equally divided into DA and DB, both as close as possible to let a,
each of the nested code to seq alternately allocated to the sub-strings a and B

algorithm design

  • Counter counter, it has not been used to represent matched ")" a "(" Number
  • Flag sgn, used to indicate a next (to be assigned to which substring

Program execution:

  • When matched to (:
    • Sgn is added to the result, a 0 indicates that the (assigned to A, 1 B allocated to the representative;
    • If the next change sgn-- or matched (, then there has been one nested, to the (points B to the substring;
    • It adds an unmatched before the parentheses, counterconduct a self-imposed;
  • When matched to ):
    • This bit )should belong to the substring and sgn different, so will sgn^1be added to result in;
    • A front bracket is matched, counterdecrement;
    • If counter != 0, then the next ()and that the bracket just finished match the connection relationship, assign them to the same sub-string can, so to change the sgnvalue;

C ++ code to achieve:

class Solution {
public:
    vector<int> maxDepthAfterSplit(string seq) {
        vector<int> result;
        short counter = 0;
        int sgn = 0;
        for(int i = 0; i < seq.size(); i++){
            if(seq[i] == '('){
                result.push_back(sgn);
                sgn ^= 1;
                counter ++;
            }
            if(seq[i] == ')'){
                result.push_back(sgn ^ 1);
                counter --;
                if(counter != 0){
                    sgn ^= 1;
                }
            }
        }
        return result;
    }
};

operation result

Guess you like

Origin www.cnblogs.com/Nreyab/p/12610657.html