-
Notifications
You must be signed in to change notification settings - Fork 5
/
ValidParentheses.java
45 lines (39 loc) · 1.41 KB
/
ValidParentheses.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
Problem Statement:
Given a string 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.
Note that an empty string is also considered valid.
Problem Link:
Valid Parentheses :https://leetcode.com/problems/valid-parentheses/description/
Solution:
https://github.com/sunnypatel165/leetcode-again/blob/master/solutions/ValidParentheses.java
Author:
Sunny Patel
https://github.com/sunnypatel165
https://www.linkedin.com/in/sunnypatel165/
*/
class Solution {
public boolean isValid(String s) {
char[] arr = s.toCharArray();
Stack stack = new Stack();
for(int i=0;i<arr.length;i++){
if(arr[i]=='(' || arr[i]=='{' || arr[i]=='[')
stack.push(arr[i]);
else{
if(arr[i]==')' && (stack.isEmpty() || (char)stack.peek()!='('))
return false;
if(arr[i]=='}' && (stack.isEmpty() || (char)stack.peek()!='{'))
return false;
if(arr[i]==']' && (stack.isEmpty() || (char)stack.peek()!='['))
return false;
stack.pop();
}
}
if(stack.isEmpty())
return true;
return false;
}
}