CC-13 : Check if parentheses are balanced.
Description:
Given a String expression containing only parentheses, check if the parentheses in input String are balanced.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| Parentheses: { | Are parentheses balanced: false |
| Parentheses: {}[] | Are parentheses balanced: true |
| Parentheses: {<>} | Are parentheses balanced: true |
| Parentheses: {()<>} | Are parentheses balanced: true |
| Parentheses: {()[]>} | Are parentheses balanced: false |
Pseudocode:
| Initialize a Deque based stack for processing purposes. |
| Initialize String pStart to hold opening brackets "({[<". |
| Initialize String pEnd to hold closing brackets ")}]>". |
| For each character in input String:
If pStart contains current character add it to the processing stack.
Else if stack is notempty, remove first character from processing stack.If it isnot the corresponding ending bracket of current character (starting bracket), the parenthesis are unbalanaced, return false.
Else if stack is empty, return false.
|
| If at end of above for loop, if stack is empty, return true. |
| Else return false. |
Code:
public boolean parenthesesChecker(String str) throws Exception{
Deque<Character> stack=new LinkedList<Character>();
char[] chr=str.toCharArray();
String pStart="({[<";
String pEnd=")}]>";
char c;
for (int idx=0;idx < chr.length; idx++) {
if (pStart.indexOf(chr[idx]) != -1){
stack.offerFirst(chr[idx]);
}else {
if (stack.peekFirst() !=null) {
c=stack.pollFirst();
if (pStart.indexOf(c) != pEnd.indexOf(chr[idx])) {
return false;
}
}else { return false;}
}
}
if (stack.size()==0) {return true;}
else { return false;}
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |