LeetCode每日一题- day10

LeetCode每日一题- day10

新手入坑LeetCode,每天打卡一道题
算法不一定很好,只是我自己的一个水平体现,做个自己刷题的记录,欢迎交流学习
(尽量AC LeetCode官方的每日一题)
欢迎交流学习!

题目:921. 使括号有效的最少添加

只有满足下面几点之一,括号字符串才是有效的:
它是一个空字符串,或者
它可以被写成 AB (A 与 B 连接), 其中 A 和 B 都是有效字符串,或者
它可以被写作 (A),其中 A 是有效字符串。
给定一个括号字符串 s ,移动N次,你就可以在字符串的任何位置插入一个括号。
例如,如果 s = “()))” ,你可以插入一个开始括号为 “(()))” 或结束括号为 “())))” 。
返回 为使结果字符串 s 有效而必须添加的最少括号数。

思路:

统计两个字符的次数的差

代码:

class Solution {
public:
    int minAddToMakeValid(string s) {
        int n = s.size();
        int res = 0,count = 0;
        for(int i = 0; i < n; i ++){
            if(s[i] == '(') res ++;
            else if(s[i] == ')') res --;
            if(res < 0) res = 0, count ++;

        }
        return res + count;
    }
};

猜你喜欢

转载自blog.csdn.net/Nmj_World/article/details/127168194