-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalancedSymbols.java
More file actions
90 lines (85 loc) · 3.26 KB
/
BalancedSymbols.java
File metadata and controls
90 lines (85 loc) · 3.26 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
85
86
87
88
89
90
import java.util.Stack;
/**
* Created by yasin_000 on 21.8.2017.
*/
public class BalancedSymbols {
//////////////////////////////////////////////
////https://www.hackerrank.com/challenges/balanced-brackets
////https://interactivepython.org/runestone/static/pythonds/BasicDS/BalancedSymbols(AGeneralCase).html
////https://leetcode.com/problems/valid-parentheses/discuss/
////
/////////11111111111//////////////////////
boolean isValid(String s){
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}
////////22222222222222222//////////////////////////
boolean isValid(String s) {
Stack<Integer> p = new Stack<>();
for(int i = 0; i < s.length(); i++) {
int q = "(){}[]".indexOf(s.substring(i, i + 1));
if(q % 2 == 1) {
if(p.isEmpty() || p.pop() != q - 1) return false;
} else p.push(q);
}
return p.isEmpty();
}
///////////3333333333333333////////////////////////
boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
// Iterate through string until empty
for(int i = 0; i<s.length(); i++) {
// Push any open parentheses onto stack
if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{')
stack.push(s.charAt(i));
// Check stack for corresponding closing parentheses, false if not valid
else if(s.charAt(i) == ')' && !stack.empty() && stack.peek() == '(')
stack.pop();
else if(s.charAt(i) == ']' && !stack.empty() && stack.peek() == '[')
stack.pop();
else if(s.charAt(i) == '}' && !stack.empty() && stack.peek() == '{')
stack.pop();
else
return false;
}
// return true if no open parentheses left in stack
return stack.isEmpty();
}
////////44444444444444////////////////////////////////
boolean isValid(String string){
Stack<String> stack = new Stack<>();
boolean balanced = true;
int index = 0;
while (index < string.length() && balanced){
String symbol = Character.toString(string.toCharArray()[index]);
if ("({[".contains(symbol))
stack.push(symbol);
else{
if (stack.isEmpty())
balanced = false;
else{
String top = stack.pop();
if (!matches(top,symbol))
balanced = false;
}
}
index++;
}
return stack.isEmpty() && balanced;
}
boolean matches(String openP, String closeP){
String open = "([{";
String close = ")]}";
return open.indexOf(openP) == close.indexOf(closeP);
}
}