LeetCode1021 delete outermost parentheses

LeetCode1021 delete outermost parentheses

Effective string is empty parentheses ( ""), "(" + A + ")" or A + B, where A and B are effective in parentheses string represents a string of + connection. For example, "", "()", "(()) ()" and "(() (()))" is a valid character string in brackets.

If a valid string S non-empty, and there it is broken into a method of S = A + B, which we call primitive (primitive), wherein A and B are non-empty string effectively parentheses.

Given a valid non-null string S, it will be considered primitive decomposition, so that: S = P_1 + P_2 + ... + P_k, wherein the bracket is a valid string P_i primitive.

S is for primitive decomposition, remove the outermost parentheses decomposition of each primitive string and returns S.

Example 1:

Input: "(() ()) (())"
Output: "() () ()"
Explanation:
the input string is "(() ()) (())", decomposition of primitive "( () ()) "+" (()) ",
delete each section to give the outermost parentheses" () () "+" () "=" () () (). "
Example 2:

Input: "(() ()) (()) (() (()))"
Output: "() () () () (())"
Explanation:
the input string is "(() () ) (()) (() (())) ", the original language of decomposition" (() ()) "+" (()) "+" (() (())) ",
delete every to give the rear portion of the outermost layer in parentheses "() ()" + "()" + "() (())" = "() () () () (())."
Example 3:

Input: "() ()"
Output: ""
Explanation:
the input string is "() ()", decomposition of primitive "()" + "()",
remove each bracket outermost portion after obtaining "" + "" = "."

prompt:

S.length <= 10000
S [I] is "(" or ")"
S is a valid string bracket

Code is shown below:

/*
**/
char * removeOuterParentheses(char * S){
    int len=strlen(S);
    int i=0,j=0;
    int sum=0;
    for(i=0;i<len;i++)
    {
        if(S[i]=='(')
            sum=sum+1;
        else
            sum=sum-1;
        if(S[i]=='('&&sum>1)//对内层的括号进行记录,放入最终输出
        {
            S[j]=S[i];
            j++;
        }
        else if(S[i]==')'&&sum>0)//对内层的右括号进行记录,放入最终输出
        {
            S[j]=S[i];
            j++;
        }
    }
    S[j]='\0';//内层括号少于外层括号,故需要加一个'\0'
    return S;
}

Harvest this question:

1.不使用栈直接进行判断
2.使用对左右括号的计数值,进行判断,左括号进行加一,右括号进行减一
  左括号是从一开始计数的,所以只要sum大于一并且确定是左括号,就加入最终输出
  右括号每次结束都是重新变为零,所以只要sum大于0并且确定是右括号就进行输出
3.由题目意思可以得到,最终要求输出的结果的符号串是小于一开始的符号串,
    故一定记得加上终结的字符
4.分析题目:
    (  (  )  (  )  )  (  (   )  )
    1  2  1  2  1  0  1   2  1  0
    根据括号的对称性可以得到'('的值大于1就开始加入,')'的值大于0就开始加入
    最终加上'\0'因为每个字符只要操作过后就不需要了,且加入的括号数量少于之前的
5.最后,本题没有使用额外的存储空间,直接使用题目一开始给的数组,使得空间复杂度也较低
Published 22 original articles · won praise 6 · views 2216

Guess you like

Origin blog.csdn.net/m0_38061255/article/details/104219509