剑指 Offer 20. 表示数值的字符串
# 剑指 Offer 20. 表示数值的字符串 (opens new window)
# 1.状态机
分析:check函数判别一个字符串是否是小数,checkint判别一个字符串是否是整数(带有前导正负号也通过)。
其中判别小数部分时要注意小数点出现的位置。特别地,如果小数点出现的位置在首字符,那么后面的整数不能包含前导正负号。
class Solution {
public boolean isNumber(String s) {
s=s.trim();
if(s.length()==0) return false;
int index=s.indexOf("e")!=-1?s.indexOf("e"):(s.indexOf("E")!=-1?s.indexOf("E"):-1);
if(index!=-1){
if(check(s.substring(0,index))||checkint(s.substring(0,index))){
if(index==s.length()-1) return false;
else{
if(checkint(s.substring(index+1))) return true;
else return false;
}
}
else return false;
}
else{
if(check(s)||checkint(s)) return true;
return false;
}
}
public boolean checkint(String s){
if(s.length()==0) return false;
if(s.charAt(0)=='+'||s.charAt(0)=='-'){
if(s.length()==1) return false;
s=s.substring(1);
}
int index=0;
while(index<s.length()){
if(s.charAt(index)>='0'&&s.charAt(index)<='9') index++;
else{
return false;
}
}
return true;
}
public boolean check(String s){
if(s.length()==0) return false;
if(s.charAt(0)=='+'||s.charAt(0)=='-'){
if(s.length()==1) return false;
s=s.substring(1);
}
int index=s.indexOf("."),start=0;
if(index==0&&index==s.length()-1) return false;
if(index==0&&checkint(s.substring(1))){
if(s.charAt(index+1)=='+'||s.charAt(index+1)=='-') return false;
return true;
}
if(index==s.length()-1&&checkint(s.substring(0,s.length()-1))){
return true;
}
while(start<index){
if(s.charAt(start)>='0'&&s.charAt(start)<='9') start++;
else return false;
}
start=index+1;
while(start<s.length()){
if(s.charAt(start)>='0'&&s.charAt(start)<='9') start++;
else return false;
}
return true;
}
}
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
编辑 (opens new window)
上次更新: 2023/12/15, 15:49:57