Likou 1047. Delete all adjacent duplicates in the string-stack

1047. Remove all adjacent duplicates in a string

Given a string S consisting of lowercase letters, the duplicate deletion operation will select two adjacent and identical letters and delete them.

Repeat the deduplication operation on S until it can no longer be deleted.

Return the final string after completing all the deduplication operations. The answer is guaranteed to be unique.

示例:

输入:"abbaca"
输出:"ca"
解释:
例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。
提示:

1 <= S.length <= 20000
S 仅由小写英文字母组成。

answer:

The typical first-in-last problem can be solved by directly building a stack on the original array.

Code:

char * removeDuplicates(char * S){
    
    
    int top = 0;
    for(int i=0;i<strlen(S);i++)
    {
    
    
        if(top==0)
        {
    
    
            S[top]=S[i];
            top++;
        }
        else
        {
    
    
            if(S[top-1]==S[i])
            {
    
    
                top--;
            }
            else
            {
    
    
                S[top]=S[i];
                top++;
            }
        }
    }
    S[top]='\0';
    return S;
}

Guess you like

Origin blog.csdn.net/xiangguang_fight/article/details/112755486