-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringParensMatch.java
More file actions
64 lines (54 loc) · 1.65 KB
/
StringParensMatch.java
File metadata and controls
64 lines (54 loc) · 1.65 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
import java.util.Stack;
public class StringParensMatch {
public static void main(String[] args) {
System.out.println(isWellFormed("sd(one{23[ser]}two)sds"));
System.out.println(isWellFormed("sd(one{23[ser}two)sds"));
}
public static boolean isWellFormed(String input) {
Stack<String> stack = new Stack<>();
String str = "({[]})";
boolean match = false;
for(int i = 0; i< input.length(); i++) {
String currentStr = String.valueOf(input.charAt(i));
//log("start scanning char at ", i);
//check if character is one I'm interested in
if(str.contains(currentStr)) {
if(stack.empty()) {
//Quit if parens is close type
if("]})".contains(currentStr)) {
match = false;
break;
}
stack.push(currentStr);
log("pushed first char", currentStr);
} else {
// Push current string if it is open type
if("([{".contains(currentStr)) {
stack.push(currentStr);
log("pushed subsequent char", currentStr);
} else {
if((stack.peek().equals("(")) && (currentStr.equals(")"))) {
match = true;
log("found matching open", currentStr);
} else if((stack.peek().equals("{")) && (currentStr.equals("}"))) {
match = true;
log("found matching open", currentStr);
} else if((stack.peek().equals("[")) && (currentStr.equals("]"))) {
match = true;
log("found matching open", currentStr);
} else {
match = false;
log("found non-matching open", currentStr);
break;
}
stack.pop();
}
}
}
}
return match;
}
public static void log(String msg, String str) {
System.out.println(msg + ":" + str);
}
}