class Solution {
public:
int minInsertions(string s) {
int insCnt = 0;
int leftCnt= 0;
int len = s.length();
int idx = 0;
while(idx<len) {
if(s[idx]=='(') {
leftCnt++;
idx++;
}
else {//是右括号
if(leftCnt>0) {//还有未匹配的左括号
leftCnt--;
}
else {//当前右括号无与之对应的左括号,插入次数+1
insCnt++;
}
if(idx<len-1&&s[idx+1]==')') {//当前右括号的下一个字符也是右括号则正确
idx+=2;
}
else {
insCnt++;
idx++;
}
}
}
//最后如果还剩余左括号,则插入次数为其2倍
insCnt+=leftCnt*2;
return insCnt;
}
};
11-15
509
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
01-28
01-05
612
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)