[LeetCode] 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.
Thought process:
There are several rules to enforce:
- There must be at least one number.
- e must come after some number and be followed by some number.
- Point cannot come after e.
- + and - can only appear in two positions: at the start of the string or right after e.
- There cannot be characters other than digits, e, point, + or -, or space.
We can use several boolean flags to make these happen.
Solution:
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 | class Solution { public boolean isNumber(String s) { s = s.trim(); boolean eSeen = false; boolean numberSeen = false; boolean pointSeen = false; boolean numberAfterE = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (Character.isDigit(c)) { numberSeen = true; numberAfterE = true; } else if (c == 'e') { if (eSeen || !numberSeen) { return false; } eSeen = true; numberAfterE = false; } else if (c == '.') { if (eSeen || pointSeen) { return false; } pointSeen = true; } else if (c == '+' || c == '-') { if (i != 0 && s.charAt(i - 1) != 'e') { return false; } } else { return false; } } return numberSeen && numberAfterE; } } |
Time complexity: O(n).
Comments
Post a Comment