# 0065. Valid Number ###### tags: `Leetcode` `Hard` `FaceBook` Link: https://leetcode.com/problems/valid-number/ ## 思路 $O(N)$ $O(1)$ 1. Declare 3 variables $seenDigit$, $seenExponent$, and $seenDot$. Set all of them to $false$. 2. Iterate over the input. 3. If the character is a digit, set $seenDigit = true$. 4. If the character is a sign, check if it is either the first character of the input, or if the character before it is an exponent. If not, return $false$. 5. If the character is an exponent, first check if we have already seen an exponent or if we have not yet seen a digit. If either is $true$, then return $false$. Otherwise, set $seenExponent = true$, and $seenDigit = false$. We need to reset $seenDigit$ because after an exponent, we must construct a new integer. 6. If the character is a dot, first check if we have already seen either a dot or an exponent. If so, return $false$. Otherwise, set $seenDot = true$. 7. If the character is anything else, return $false$. 8. At the end, return $seenDigit$. This is one reason why we have to reset $seenDigit$ after seeing an exponent - otherwise an input like "21e" would be incorrectly judged as valid. ## Code ```java= class Solution { public boolean isNumber(String s) { boolean seenDigit = false; boolean seenExponent = false; boolean seenDot = false; for(int i = 0;i < s.length();i++){ char curr = s.charAt(i); if(Character.isDigit(curr)){ seenDigit = true; } else if(curr=='+' || curr=='-'){ if(i>0 && s.charAt(i-1)!='E' && s.charAt(i-1)!='e'){ return false; } } else if(curr=='E' || curr=='e'){ if(seenExponent || !seenDigit) return false; seenExponent = true; seenDigit = false; } else if(curr=='.'){ if(seenDot || seenExponent) return false; seenDot = true; } else{ return false; } } return seenDigit; } } ```