其他分享
首页 > 其他分享> > LeetCode 1541. Minimum Insertions to Balance a Parentheses String

LeetCode 1541. Minimum Insertions to Balance a Parentheses String

作者:互联网

原题链接在这里:https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/

题目:

Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if:

In other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis.

You can insert the characters '(' and ')' at any position of the string to balance it if needed.

Return the minimum number of insertions needed to make s balanced.

Example 1:

Input: s = "(()))"
Output: 1
Explanation: The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be "(())))" which is balanced.

Example 2:

Input: s = "())"
Output: 0
Explanation: The string is already balanced.

Example 3:

Input: s = "))())("
Output: 3
Explanation: Add '(' to match the first '))', Add '))' to match the last '('.

Constraints:

题解:

count is number of ( encountered.

When we encounter a (, simply do count++.

When we encounter a ). First we need to check if there are 2 consecutive )).

If yes, we need to move index++ and minus count by 1.

If no, then it is a simple ), we need to make it 2 consecutive )) and minus count by 1.

Time Complexity: O(n). n = s.length().

Space: O(1).

AC Java:

 1 class Solution {
 2     public int minInsertions(String s) {
 3         if(s == null || s.length() == 0){
 4             return 0;
 5         }
 6         
 7         int count = 0;
 8         int res = 0;
 9         for(int i = 0; i < s.length(); i++){
10             char c = s.charAt(i);
11             if(c == '('){
12                 count++;
13             }else{
14                 if(i < s.length() - 1 && s.charAt(i + 1) == ')'){
15                     i++;
16                     if(count > 0){
17                         count--;
18                     }else{
19                         res++;
20                     }
21                 }else{
22                     res++;
23                     if(count > 0){
24                         count--;
25                     }else{
26                         res++;
27                     }
28                 }   
29             }
30         }
31         
32         return res + count * 2;
33     }
34 }

类似Minimum Add to Make Parentheses Valid.

标签:count,Parentheses,Insertions,String,++,res,parenthesis,balanced,string
来源: https://www.cnblogs.com/Dylan-Java-NYC/p/16212135.html