LeetCode 65: Valid Number Solution
Master LeetCode problem 65 (Valid Number), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
65. Valid Number
Problem Explanation
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)
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 65 (Valid Number)?
This page provides optimized solutions for LeetCode problem 65 (Valid Number) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 65 (Valid Number)?
The time complexity for LeetCode 65 (Valid Number) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 65 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 65 in Java, C++, or Python.