-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution100.java
87 lines (85 loc) · 2.13 KB
/
Solution100.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
/*
Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
*/
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Solution {
// 正则表达式 time:776ms
public boolean isNumber(String s) {
Pattern pattern = Pattern.compile("[-+]?(\\d+\\.?|\\.\\d+)\\d*(e[-+]?\\d+)?");
Matcher mat = pattern.matcher(s.trim());
return mat.matches();
}
// time:484ms
public boolean isNumber(String s) {
s = s.trim();
if (s.startsWith("-") || s.startsWith("+")) {
s = s. substring(1);
}
if ("".equals(s)) {
return false;
}
int dotPos = -1, ePos = -1;
for (int i = 0; i < s.length(); i++) {
if (dotPos == -1 && s.charAt(i) == '.') {
dotPos = i;
} else if (ePos == -1 && s.charAt(i) == 'e') {
ePos = i;
if (i+1 < s.length() && (s.charAt(i+1) == '-' || s.charAt(i+1) == '+')) {
i++;
}
} else {
if (Character.isDigit(s.charAt(i))) {
continue;
} else {
return false;
}
}
}
//xxx.xxexx
String startStr, midStr, endStr;
if (dotPos != -1 && ePos == -1) {
startStr = s.substring(0, dotPos);
endStr = s.substring(dotPos+1);
if (startStr.length() < 1 && endStr.length() < 1) {
return false;
}
} else if (dotPos == -1 && ePos != -1) {
startStr = s.substring(0, ePos);
if (startStr.length() < 1) {
return false;
}
endStr = s.substring(ePos+1);
if (endStr.startsWith("-") || endStr.startsWith("+")) {
endStr = endStr.substring(1);
}
if (endStr.length() < 1) {
return false;
}
} else if (dotPos != -1 && ePos != -1) {
if (dotPos >= ePos) {
return false;
}
startStr = s.substring(0, dotPos);
midStr = s.substring(dotPos+1, ePos);
if (startStr.length() < 1 && midStr.length() < 1) {
return false;
}
endStr = s.substring(ePos+1);
if (endStr.startsWith("-") || endStr.startsWith("+")) {
endStr = endStr.substring(1);
}
if (endStr.length() < 1) {
return false;
}
}
return true;
}
}