forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
_65.java
58 lines (53 loc) · 1.64 KB
/
_65.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
package com.fishercoder.solutions;
/**
* 65. Valid Number
*
* 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.
*/
public class _65 {
/**credit: https://discuss.leetcode.com/topic/9490/clear-java-solution-with-ifs*/
public static class Solution1 {
public boolean isNumber(String s) {
s = s.trim();
boolean pointSeen = false;
boolean eSeen = false;
boolean numberSeen = false;
boolean numberAfterE = true;
for (int i = 0; i < s.length(); i++) {
if ('0' <= s.charAt(i) && s.charAt(i) <= '9') {
numberSeen = true;
numberAfterE = true;
} else if (s.charAt(i) == '.') {
if (eSeen || pointSeen) {
return false;
}
pointSeen = true;
} else if (s.charAt(i) == 'e') {
if (eSeen || !numberSeen) {
return false;
}
numberAfterE = false;
eSeen = true;
} else if (s.charAt(i) == '-' || s.charAt(i) == '+') {
if (i != 0 && s.charAt(i - 1) != 'e') {
return false;
}
} else {
return false;
}
}
return numberSeen && numberAfterE;
}
}
public static class Solution2 {
/** credit: https://discuss.leetcode.com/topic/2973/java-solution-with-one-line */
public boolean isNumber(String s) {
return s.matches("(\\s*)[+-]?((\\.[0-9]+)|([0-9]+(\\.[0-9]*)?))(e[+-]?[0-9]+)?(\\s*)");
}
}
}