# 1541. Minimum Insertions to Balance a Parentheses String ###### tags: `Leetcode` `Medium` `Parentheses` Link: https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/ ## 思路 和[0921. Minimum Add to Make Parentheses Valid](https://hackmd.io/BW_TqN0oTsq6f0gxlYxXHw)的思路差不多,用余量做 但差别在于要区分只有一个')'和有'))'的情况 ## Code ```java= class Solution { public int minInsertions(String s) { int left = 0; int ans = 0; for(int i=0; i<s.length(); i++){ if(s.charAt(i)=='(') left++; else{ if(i+1<s.length() && s.charAt(i+1)==')') i+=1; else ans++; if(left==0) ans++; else left--; } } ans += left*2; return ans; } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up