forked from yuzhangcmu/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTokenizer.java
executable file
·90 lines (76 loc) · 2.72 KB
/
Tokenizer.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package Algorithms;
import java.util.ArrayList;
public class Tokenizer {
public enum State {
GAP,
INSIDE_STRING,
INSIDE_QUATER
}
public static void main(String[] strs) {
System.out.println("Test case");
String str = "Test case";
str = "util.exe -file abc -s [abc dd]]] \"efg []\"\"]z\"";
System.out.println(tokenize(str));
}
public static void AddToken(String token, ArrayList<String> list) {
if (!token.isEmpty()) {
list.add(token);
}
}
public static ArrayList<String> tokenize(String input) {
ArrayList<String> ret = new ArrayList<String>();
State state = State.GAP;
String token = "";
char divider = ' ';
int len = input.length();
for (int i = 0; i < len; i++) {
char c = input.charAt(i);
switch(state) {
case GAP:
if (c == ' ') {
continue;
} else {
if (c == '[' || c == '"') {
if (c == '[') {
divider = ']';
} else {
divider = c;
}
state = State.INSIDE_QUATER;
} else {
state = State.INSIDE_STRING;
// Add c to the current token;
token = token + c;
}
}
break;
case INSIDE_QUATER:
if (c == divider) {
// End of the string.
if (i == len - 1 || input.charAt(i + 1) == ' ') {
state = State.GAP;
AddToken(token, ret);
token = "";
continue;
} else if (input.charAt(i + 1) == divider) {
i++;
}
}
token = token + c;
break;
case INSIDE_STRING:
if (c == ' ') {
state = State.GAP;
AddToken(token, ret);
token = "";
continue;
}
token = token + c;
break;
default:
break;
}
}
return ret;
}
}