LeetCode_1249. 移除无效的括号

使用单调栈

char *minRemoveToMakeValid(char *s)
{
    int n = strlen(s);
    int stack[100001] = {0};
    int top = 0, retSize = 0, cur = 0;
    char *ret = (char *)calloc((n + 1), sizeof(char));
    for (int i = 0; i < n; i++){
        if(!isalpha(s[i])){
            if(top > 0 && s[i] == ')' && s[stack[top - 1]] == '('){
                top--;
                continue;
            }
            stack[top++] = i;
        }
    }
    for (int i = 0; i < n; i++){
        if(isalpha(s[i])){
            ret[retSize++] = s[i];
            continue;
        }
        if(cur < top && i == stack[cur]){
            cur++;
            continue;
        }
        ret[retSize++] = s[i];
    }
    ret[retSize] = '\0';
    return ret;
}

由于本人还处于学习阶段,如有不足请大家指出

你可能感兴趣的:(leetcode,算法,职场和发展)