Github仓库地址:https://github.com/Damaer/CodeSolution 笔记地址:https://damaer.github.io/CodeSolution/ 仓库介绍:刷题仓库:CodeSolution

请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
示例1
输入
"123.45e+6"
返回值
true
这道题咋一看,有点复杂,case很多,主要是分析好判断分支,我们可以定义几个变量:
hashNum: 是否已经有数字hashE:是否已经有EhasSign:是否已经有符号hasDot:是否已经有小数点首先,初始化当前的索引index =0,字符串头部的空格需要跳过。
hasNum = true,并且索引后移,直到不是数字的时候,跳出循环。index是否合法,不合法直接breakc:falsehasDot置为truehasSign置为true,表示符号出现过E,或者前面没有数字,直接返回falsehasE置为true,其他的置为false,也就是E后面可以继续出现符号数字和小数点了c是e或者E:c是“+”或者“-”:c是小数点“.”c为空格,直接跳出循环false public boolean isNumeric(String str) {
int size = str.length();
int index= 0 ;
// 默认全部是false
boolean hashNum=false ,hasE=false ,hasSign=false ,hasDot=false;
// 跳过空格
while(index<size&&str.charAt(index)==' '){
index++;
}
while(index<size){
while(index<size&&str.charAt(index)>='0'&& str.charAt(index)<='9'){
index++;
// 表示前面有数字
hashNum = true;
}
// 到末尾直接跳出
if(index==size){
break;
}
char c = str.charAt(index);
if(c=='e'||c=='E'){
// 前面有E或者没有数字在前面
if(hasE||!hashNum){
return false;
}
hasE = true;
// 出现E了后面又可以出现数字了
hashNum = false;
hasSign = false;
hasDot = false;
}else if(c=='+'||c=='-'){
if(hasSign||hashNum||hasDot){
return false;
}
hasSign = true;
}else if(c=='.'){
if(hasDot||hasE){
return false;
}
hasDot =true;
}else if(c==' '){
break;
}else{
return false;
}
index++;
}
// 跳过空格
while(index<size&&str.charAt(index)==' '){
index++;
}
return hashNum &&index==size;
}
总结一下
这道题,其实本质是转态的切换,最最重要的一点,是E出现之后,其实小数点和符号,和数字,都是可以再出现的,可以理解为E就是一个分割线。
【作者简介】:
秦怀,公众号【秦怀杂货店】作者,技术之路不在一时,山高水长,纵使缓慢,驰而不息。个人写作方向:Java源码解析,JDBC,Mybatis,Spring,redis,分布式,剑指Offer,LeetCode等,认真写好每一篇文章,不喜欢标题党,不喜欢花里胡哨,大多写系列文章,不能保证我写的都完全正确,但是我保证所写的均经过实践或者查找资料。遗漏或者错误之处,还望指正。
平日时间宝贵,只能使用晚上以及周末时间学习写作 - END -