-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStringRecognizer.java
74 lines (62 loc) · 2.09 KB
/
StringRecognizer.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
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
import java.util.*;
public class StringRecognizer {
public static boolean isRecognizable(String str) {
switch (str) {
case "aca":
return matchAca(str);
case "bcb":
return matchBcb(str);
case "abcba":
return matchAbcba(str);
case "abbcbba":
return matchAbbcbba(str);
default:
return false;
}
}
private static boolean matchAca(String str) {
if (str.length() == 3) {
return str.charAt(0) == 'a' && str.charAt(2) == 'a' && str.charAt(1) == 'c';
}
return false;
}
private static boolean matchBcb(String str) {
if (str.length() == 3) {
return str.charAt(0) == 'b' && str.charAt(2) == 'b' && str.charAt(1) == 'c';
}
return false;
}
private static boolean matchAbcba(String str) {
if (str.length() == 5) {
return str.charAt(0) == 'a' && str.charAt(4) == 'a'
&& str.charAt(1) == 'b' && str.charAt(3) == 'b'
&& str.charAt(2) == 'c';
}
return false;
}
private static boolean matchAbbcbba(String str) {
if (str.length() == 7) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < 3; i++) {
stack.push(str.charAt(i));
}
for (int i = 4; i < 7; i++) {
if (stack.isEmpty() || stack.pop() != str.charAt(i)) {
return false;
}
}
return true;
}
return false;
}
public static void main(String[] args) {
String[] testStrings = {"aca", "bcb", "abcba", "abbcbba"};
for (String str : testStrings) {
if (isRecognizable(str)) {
System.out.println(str + " is recognized.");
} else {
System.out.println(str + " is not recognized.");
}
}
}
}