Search code examples
javaalgorithmstackparentheses

Checking Duplicate Parenthesis Using stacks in java


The code is to check weather Duplicate parenthesis exist or not .. I am getting true for every string. I am unable to find where I am wrong

public class DuplicatePar {
    public static void main(String[] args) {
        String str = "((a+b)+c)";
        System.out.println(dupliPar(str));
    }
    public static boolean dupliPar(String str){
        Stack<Character> s = new Stack<>();
        for(int i = 0; i<str.length();i++){
            if(str.charAt(i) != ')'){
                s.push(str.charAt(i));
            }
            if(str.charAt(i) == ')' && s.peek() != '('){
                while(s.peek() !='('){                                      
                    s.pop();
                }
                s.pop();
            }
          
            else{
                return true;
            }
        }
      return false;
    }
}

Solution

  • As written -

            if(str.charAt(i) != ')'){
                s.push(str.charAt(i));
            }
            if(str.charAt(i) == ')' && s.peek() != '('){
                while(s.peek() !='('){                                      
                    s.pop();
                }
                s.pop();
            }
          
            else{
                return true;
            }
    

    Suppose the first char is '(', The condition of the first 'if' is true (it's not a close parenthesis) so we execute the controlled statement (push to stack).

    We're now done with that 'if'. The second 'if' has a false condition so we execute the associated 'else' clause and immediately return a 'true' result.

    With 'else' added:

            if(str.charAt(i) != ')'){
                s.push(str.charAt(i));
            }
            else if(str.charAt(i) == ')' && s.peek() != '('){
                while(s.peek() !='('){                                      
                    s.pop();
                }
                s.pop();
            }
          
            else{
                return true;
            }
    

    Again, suppose the first char is '(', The condition of the first 'if' is true (it's not a close parenthesis) so we execute the controlled statement (push to stack).

    And therefore we do not execute the 'else' clause of the first 'if' statment. The 'else' clause is the entire second if-else construction. Thus we don't return the incorrect result, but keep processing the input string.


    That's the solution to the specific problem you reported, but I am not convinced the code works in all cases. Consider the input string ")(" for example.