Sunday, 22 December 2019

Check Duplicate Parenthesis in String

Given a balanced expression, find if it contains duplicate parenthesis or not. A set of parenthesis are duplicate if the same subexpression is surrounded by multiple parenthesis.


 import java.util.*;

class GFG {
    static String check(String s)
    {
        Stack<Character>st=new Stack<>();
        for(int i=0;i<s.length();i++)
        {
            if(s.charAt(i)==')')
            {
                int ele=0;
                while(!st.isEmpty()&&st.peek()!='(')
                {
                    st.pop();
                    ele++;
                }
                if(ele<1)
                  return "Duplicate Parenthesis";
                else
                {
                    if(!st.isEmpty())
                     st.pop();
                }
            }
            else
            st.push(s.charAt(i));
        }
        return "Not Duplicate";
    }
    public static void main (String[] args) {
        Scanner sc=new Scanner(System.in);
        String s=sc.next();
        System.out.println(check(s));
    }
}