0% found this document useful (0 votes)
8 views1 page

Valid Parantehsis

Uploaded by

ompanem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views1 page

Valid Parantehsis

Uploaded by

ompanem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

class Solution {

public boolean isValid(String s) {


char firstChar = ' ';
char [] charArray = s.toCharArray();
Stack<Character> stack = new Stack<>();
for(int i =0; i<charArray.length; i++){
char ch = charArray[i];

if(ch == '('){
stack.push(ch);
firstChar = stack.peek();
}

if(ch == '['){
stack.push(ch);
firstChar = stack.peek();
}

if(ch == '{'){
stack.push(ch);
firstChar = stack.peek();
}

if(ch == ')' && firstChar == '('){


if(stack.isEmpty()){ //check if amount of left and right
paranthesis are equal
return false;
}
stack.pop();
}

if(ch == ']' && firstChar == '['){


if(stack.isEmpty()){ //check if amount of left and right
paranthesis are equal
return false;
}
stack.pop();
}

if(ch == '}' && firstChar == '{'){


if(stack.isEmpty()){ //check if amount of left and right
paranthesis are equal
return false;
}
stack.pop();
}

}
return stack.isEmpty();
}
}

You might also like