Learn-dsa..in 30 days!



























CC-14 : Check if parentheses pairs are duplicate.

Description:

Given a String expression containing only parentheses, check if duplicate pairs (un-necessary pairs) of brackets are present.

Test cases and expected outputs:

Input Parameters Expected outputs
Expression: ((x+y))+z Are parentheses duplicate: true
Expression: (x+y) Are parentheses duplicate: false
Expression: ((x+y)+((z))) Are parentheses duplicate: true

Pseudocode:

Initialize a Deque based stack for processing purposes.
If input String length is less than 3, return false, as duplicate pairs of parentheses are not possible.
For each character in input String:
If current character is not ‘)‘, add it to the stack.
Else if top element of stack is ‘(‘, return true.
Else while top character of stack is not ‘(‘, remove it from the stack.
Pop top element of the stack.
Return false from the program.


Code:

public boolean duplicateChecker(String str) throws Exception{
	Deque<Character> stack=new LinkedList<Character>();	
	if (str.length()<=3) { return false;}
	char[] chr=str.toCharArray();
	char c;
	for (int idx=0;idx < chr.length; idx++) {
		c=chr[idx];
		if (c != ')') {
			stack.offerFirst(c);
		} else {
			if (stack.peekFirst()=='(') {
				return true;
			}
			while (stack.peekFirst()!='(') {
				stack.pollFirst();
			}
		stack.pollFirst();
		}
	}
	return false;
}

Click here to download and run code and test cases !