65. Valid Number
Explanation
To solve this problem, we can use a finite state machine approach. We define different states based on the characters encountered in the input string. By transitioning between states based on the characters, we determine if the input string represents a valid number.
We start in the initial state and move through different states based on the characters encountered. The possible states are:
- Start: Initial state.
- Sign: Optional sign '+' or '-'.
- Integer: Integer part of the number.
- Dot: Decimal point.
- Decimal: Decimal part of the number.
- Exp: Exponential notation 'e' or 'E'.
- ExpSign: Optional sign in the exponent.
- ExpInteger: Integer part of the exponent.
- End: Final state.
We iterate over the characters in the input string and transition between states accordingly. At the end, if we are in a valid final state (End) or in one of the acceptable final states (Integer, Decimal, ExpInteger), then the input string is a valid number.
- Time complexity: O(n) where n is the length of the input string.
- Space complexity: O(1)
class Solution {
public boolean isNumber(String s) {
if (s == null || s.length() == 0) {
return false;
}
s = s.trim();
boolean seenNum = false;
boolean seenDot = false;
boolean seenExp = false;
boolean seenSign = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
seenNum = true;
} else if (c == '.') {
if (seenDot || seenExp) {
return false;
}
seenDot = true;
} else if (c == 'e' || c == 'E') {
if (seenExp || !seenNum) {
return false;
}
seenExp = true;
seenNum = false;
seenSign = false;
} else if (c == '+' || c == '-') {
if (seenNum || seenSign) {
return false;
}
seenSign = true;
} else {
return false;
}
}
return seenNum;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.