-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidParanthese.java
More file actions
84 lines (72 loc) · 2.27 KB
/
ValidParanthese.java
File metadata and controls
84 lines (72 loc) · 2.27 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import java.util.Stack;
/**
* Created by devpriyadave on 2/18/18.
*
* Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
Example ({{[]}})
(({))
Logic:
Use stacks
*/
public class ValidParanthese {
public boolean myisValidUsingStacks(String s) {
if(s == "" || s.length()%2 < 0) {
return false;
}
Stack<Character> stack = new Stack<Character>();
for(int i=0; i< s.length(); i++) {
if(stack.isEmpty() || !isPair(stack.peek(),s.charAt(i)))
stack.push(s.charAt(i));
else
stack.pop();
}
return stack.isEmpty();
}
private boolean isPair(Character peek, Character c) {
switch (peek) {
case '(':
if(c!=')')
return false;
break;
case '{':
if(c!='}')
return false;
break;
case '[':
if(c!=']')
return false;
break;
default:
return false;
}
return true;
}
public boolean isValid(String s) {
char[] stack = new char[s.length()];
int head = 0;
for (char c : s.toCharArray()) {
if (c == '(') {
stack[head++] = c;
} else if (c == '[') {
stack[head++] = c;
} else if (c == '{') {
stack[head++] = c;
} else if (c == ')') {
if (head == 0) return false;
if (stack[--head] != '(') return false;
} else if (c == ']') {
if (head == 0) return false;
if (stack[--head] != '[') return false;
} else if (c == '}') {
if (head == 0) return false;
if (stack[--head] != '{') return false;
}
}
return head == 0;
}
public static void main(String [] args) {
ValidParanthese validParanthese = new ValidParanthese();
System.out.println(validParanthese.myisValidUsingStacks("(){}"));
}
}