2020-03-24

class Solution {
public:
    string minRemoveToMakeValid(string s) {
    stack<string> char_stack;
    stack<int> index_stack;
    int length = s.length();
    if (length == 0)
        return s;
    int begin = 0, end = 1;
    for (; end <= length; end++) {
        string sub_str = s.substr(end-1, 1);
        if (sub_str == ")") {
            if (char_stack.empty() && index_stack.empty()) {
                char_stack.push(sub_str);
                index_stack.push(end - 1);
            }

            else if (char_stack.top() == "(") {
                char_stack.pop();
                index_stack.pop();
            }
            else {
                char_stack.push(sub_str);
                index_stack.push(end - 1);
            }
        }
        else if (sub_str == "(") {
            char_stack.push(sub_str);
            index_stack.push(end - 1);
        }
        else
            continue;

    }
    string new_str;
    if (char_stack.empty() && index_stack.empty())
        new_str= s;
    else {
        
        stack<int> re_index_stack;
        while (!index_stack.empty()) {
            re_index_stack.push(index_stack.top());
            index_stack.pop();
        }
            
        end = 1;

        for (; end <= length; end++) {
            //cout << end<<endl;
            if (!re_index_stack.empty()) {
                if ((end - 1) == re_index_stack.top()) {
                    re_index_stack.pop();
                    continue;
                }

                else {
                    new_str += s.substr(end - 1, 1);
                }
            }

            else {
                new_str += s.substr(end - 1, 1);
            }   
        }
    
        
    }
    return new_str;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容