Leetcode 65. Valid Number

题目

65. Valid Number

  • Difficulty: Hard
  • Total Accepted: 99.5K
  • Total Submissions: 753.7K

Validate if a given string can be interpreted as a decimal number.

Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
" -90e3 " => true
" 1e" => false
"e3" => false
" 6e-1" => true
" 99e2.5 " => false
"53.5e93" => true
" --6 " => false
"-+3" => false
"95a54e53" => false

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number:

Numbers 0-9
Exponent - “e”
Positive/negative sign - “+”/“-“
Decimal point - “.”

Of course, the context of these characters also matters in the input.

解题报告

AC 截图

题目大意

检查一个字符串的内容(在删去前后缀的空格后)是否是一个合法的十进制数。

解题思路

该题可以通过将字符串分块来令问题化为简单的子问题的组合。首先考虑有 E 的字符串,则我们只需要判断左边是否为一个合法小数,右边是否为一个合法整数。

对于一个小数字符串,我们只需要判断小数点左边和右边是否为一个合法整数。

对于一个整数字符串,我们只需要判断除了符号外,其他字符是否是一个合法数字即可。

坑点

1..3 都是合法的数字。

题解

AC 截图

C++ 代码

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
class Solution {
public:
bool isNumber(string s) {
int front = 0, last = s.size() - 1;
for (; front < last && s[front] == ' '; ++front);
for (; front < last && s[last] == ' '; --last);
s = s.substr(front, last - front + 1);

int indexOfE;
if ((indexOfE = s.find('e')) != -1) {
if (indexOfE != s.size() - 1) {
return (isFraction(s.substr(0, indexOfE)) &&
isInteger(s.substr(indexOfE + 1), true));
}
return false;
} else {
return isFraction(s);
}
return false;
}

bool isFraction(string s) {
s = s.substr(s[0] == '+' || s[0] == '-');
int indexOfDot = s.find('.');
if (indexOfDot != -1 && indexOfDot != s.size() - 1) {
return isInteger(s.substr(0, indexOfDot), false, true) && isInteger(s.substr(indexOfDot + 1), false, true);
}
return isInteger(s);
}

bool isInteger(string s, bool checkMinus = false, bool allowZero = false) {
if (checkMinus) {
s = s.substr(s[0] == '+' || s[0] == '-');
}

for (const auto &iter : s) {
if (iter > '9' || iter < '0') {
return false;
}
}

return allowZero || s.size();
}
};
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×