[Leetcode] 921: The least addition to make parentheses effective

daily progress

  • Find a substring of a string: str.substring(int beginindex, int endindex)

topic

Bracketed strings are only valid if one of the following is true:

  • it is an empty string, or
  • It can be written as AB (A concatenated with B), where A and B are both valid strings, or
  • It can be written as (A), where A is a valid string.

Given a bracket string s, move N times and you can insert a bracket anywhere in the string.

  • For example, if s = "()))", you can insert an opening bracket as "(()))"or closing bracket as "())))".

Returns the minimum number of parentheses that must be added for the result string s to be valid.

Source: LeetCode
Link: https://leetcode.cn/problems/minimum-add-to-make-parentheses-valid
The copyright belongs to Leetcode Network. For personal study only, non-commercial use.

answer

Method 1: Greedy Algorithm

  • Iterate through each character of the string
    • If the character is (, add 1 to the number of left brackets.
    • If the character is ), and the current number of left brackets is not 0, it means that there are brackets that can match the right brackets. Therefore, decrement the number of opening brackets by 1.
    • If the character is ), and the current number of left brackets is 0. At this time, no opening bracket can match the closing bracket, and the opening bracket needs to be added. Therefore, the number of operations is increased by 1.
  • In addition, if the number of left parentheses is not 0 after the traversal left_num, it means that there are remaining left parentheses, and the same number of right parentheses needs to be added to match them. Therefore, the number of operations increases left_num.
class Solution {
    
    
    public int minAddToMakeValid(String s) {
    
    
        int left_num = 0, ans = 0;
        char[] arr = s.toCharArray();

        for (char x : arr){
    
    
            if (x == '(')
                left_num += 1;
            else if (left_num != 0)
                left_num -= 1;
            else
                ans += 1;
        }

        return left_num + ans;
    }
}

The running result is shown in the figure below:
result

Method 2: Recursive algorithm
This method is similar to the quick sort algorithm. The string is continuously divided into substrings, and the number of operations required to turn each substring into a valid parenthesis is calculated, and finally summed.
This method requires attention : at the beginning, it is necessary to remove the substring that can be matched. Because after being divided into different substrings, the parentheses in different substrings cannot be matched, so these substrings need to be excluded first.

class Solution {
    
    
    int ans = 0;

    public int minAddToMakeValid(String s) {
    
    
        while(s.contains("()")){
    
    
            s = s.substring(0, s.indexOf("()")) + s.substring(s.indexOf("()")+2, s.length());
        }

        partition(s, 0, s.length());
        return ans;
    }

    public void partition(String s, int beginindex, int endindex){
    
    
        String spart = s.substring(beginindex, endindex);

        if (spart.contains(")(")){
    
    
            partition(spart, 0, spart.indexOf(")(")+1);
            partition(spart, spart.indexOf(")(")+1, spart.length());
            return;
        }

        char[] arr = spart.toCharArray();
        int anspart = 0;

        for (char x : arr){
    
    
            if (x == '(')
                anspart += 1;
            else
                anspart -= 1;
        }

        ans += Math.abs(anspart);
    }
}

Guess you like

Origin blog.csdn.net/weixin_45800258/article/details/127166433