Given a string
S
of '('
and ')'
parentheses, we add the minimum number of parentheses ( '('
or ')'
, and in any positions ) so that the resulting parentheses string is valid.Example:
Input: str="())"
Output: 1
Approach
Java
public class MinAddMakeParenthesesValid {public static void main(String[] args) {String str = "())";System.out.println(minAddToMakeValid(str));}// function to find the number// of add to make string validstatic int minAddToMakeValid(String s) {int cnt = 0;int n = s.length();int open = 0;// iterate till the length of stringfor (int i = 0; i < n; i++) {// if open bracket push into// the stackif (s.charAt(i) == '(')open++;// if closing bracketelse if (s.charAt(i) == ')') {if (open == 0)cnt++;elseopen--;}}cnt = cnt + open;// return the countreturn cnt;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the number//of add to make string validint minAddToMakeValid(string s){stack<char> st;int cnt=0;int n=s.size();//iterate till the length of stringfor(int i=0;i<n;i++){//if open bracket push into//the stackif(s[i]=='(')st.push(s[i]);//if closing bracketelse if(s[i]==')'){//if stack is empty increment//the countif(st.empty())cnt++;//else pop from the stackelsest.pop();}}//uodate the countcnt+=st.size();//return the countreturn cnt;}int main(){string str="())";cout<<minAddToMakeValid(str);return 0;}
No comments:
Post a Comment