Type Here to Get Search Results !

Stack Valid Parentheses in Java leetcode 100% Correct solution.

0

 Stack Valid Parentheses in java leetcode solution.


Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
 

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "()[]{}"
Output: true

Example 3:

Input: s = "(]"
Output: false
 

Constraints:

1 <= s.length <= 104
s consists of parentheses only '()[]{}'.

Latest Engineering Or IT Jobs Telegram Channel - Click Here

Valid parentheses code in Java :-

class Solution {
	public boolean isValid(String s) {
		Stack<Character> stack = new Stack<>();
		for(int i=0;i<s.length();i++){
			char c = s.charAt(i);
			if(c=='(')
				stack.push(')');
			else if(c=='{')
				stack.push('}');
			else if(c=='[')
				stack.push(']');
			else if(c==')'  && stack.size()>0 && stack.peek()==')')
				stack.pop();
			else if(c=='}'  && stack.size()>0 && stack.peek()=='}')
				stack.pop();
			else if(c==']'  && stack.size()>0 && stack.peek()==']')
				stack.pop();
			else
				return false;            
		}
		if(stack.size()>0)
			return false;
		return true;
	}
}


Run Code - Click Here

Post a Comment

0 Comments