Leetcode每日一题:使括号有效的最少添加(括号匹配)

文章目录


题目

只有满足下面几点之一,括号字符串才是有效的:

  • 它是一个空字符串,或者
  • 它可以被写成 AB (A 与 B 连接), 其中 A 和 B 都是有效字符串,或者
  • 它可以被写作 (A),其中 A 是有效字符串。

返回 为使结果字符串 s 有效而必须添加的最少括号数。

示例 1:

输入:s = “())”
输出:1

示例 2:

输入:s = “(((”
输出:3


解析

题目难度其实配不上中等二字,栈 or 贪心都可以解决,本篇博客旨在记录评论区中见到的一个有趣想法。

贪心

class Solution {
    
    
public:
    int minAddToMakeValid(string s) {
    
    
        int num_left = 0;
        int res = 0;
        for(char i : s){
    
    
            if(i == '('){
    
    
                num_left++;
            }
            else{
    
     // i == )
                if(num_left > 0) num_left--;
                else res++;
            }
        }
        return res += num_left;
    }
};

趣解

class Solution {
    
    
public:
    int minAddToMakeValid(string s) {
    
    
        while(s.find("()") != s.npos) {
    
    
        	// 将()替换为空字符串,并循环这一行为直至没有成对括号出现
            s = s.replace(s.find("()"),2,"");
        }
        return s.size();
    }
};

循环消去 s 中的匹配括号,剩下的当然是不匹配的括号,也就是需要加多少个括号才能让它们匹配啦~

猜你喜欢

转载自blog.csdn.net/Jormungand_V/article/details/127167232