这道题太烦了,看了很久,先不管它了
题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100"、“5e2”、"-123"、“3.1416”、"-1E-16"、“0123"都表示数值,但"12e”、“1a3.14”、“1.2.3”、"±5"及"12e+5.4"都不是。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/biao-shi-shu-zhi-de-zi-fu-chuan-lcof
参考解法1
class Solution {
public boolean isNumber(String s) {
if(s == null || s.length() == 0){
return false;
}
//标记是否遇到相应情况
boolean numSeen = false;
boolean dotSeen = false;
boolean eSeen = false;
char[] str = s.trim().toCharArray();
for(int i = 0;i < str.length; i++){
if(str[i] >= '0' && str[i] <= '9'){
numSeen = true;
}else if(str[i] == '.'){
//.之前不能出现.或者e
if(dotSeen || eSeen){
return false;
}
dotSeen = true;
}else if(str[i] == 'e' || str[i] == 'E'){
//e之前不能出现e,必须出现数
if(eSeen || !numSeen){
return false;
}
eSeen = true;
numSeen = false;//重置numSeen,排除123e或者123e+的情况,确保e之后也出现数
}else if(str[i] == '-' || str[i] == '+'){
//+-出现在0位置或者e/E的后面第一个位置才是合法的
if(i != 0 && str[i-1] != 'e' && str[i-1] != 'E'){
return false;
}
}else{//其他不合法字符
return false;
}
}
return numSeen;
}
}
作者:yangshyu6
链接:https://leetcode-cn.com/problems/biao-shi-shu-zhi-de-zi-fu-chuan-lcof/solution/javaban-ben-ti-jie-luo-ji-qing-xi-by-yangshyu6/
参考解法2
主要的思路就是,首先把带符号的整数先去掉,然后因为e的后面不允许有.小数,小数后面可以有e。 所以去判断如果==’.’。如果等于则把后面的无符号的整数去掉。如果又碰到了e。也去把后面的有符号的整数去掉。 如果结束后,最后index不是最后一位,那么则为false。 如果结束后,最后index是最后一位,则为true。 不符合条件的走不到最后,例如13.45a6 .最后只会走到a就会结束,所以为false。
class Solution {
private int index = 0;//全局索引
private boolean scanUnsignedInteger(String str) {
//是否包含无符号数
int before = index;
while(str.charAt(index) >= '0' && str.charAt(index) <= '9')
index++;
return index > before;
}
private boolean scanInteger(String str) {
//是否包含有符号数
if(str.charAt(index) == '+' || str.charAt(index) == '-')
index++;
return scanUnsignedInteger(str);
}
public boolean isNumber(String s) {
//空字符串
if(s == null || s.length() == 0)
return false;
//添加结束标志
s = s + '|';
//跳过首部的空格
while(s.charAt(index) == ' ')
index++;
boolean numeric = scanInteger(s); //是否包含整数部分
if(s.charAt(index) == '.') {
index++;
//有小数点,处理小数部分
//小数点两边只要有一边有数字就可以,所以用||,
//注意scanUnsignedInteger要在前面,否则不会进
numeric = scanUnsignedInteger(s) || numeric;
}
if((s.charAt(index) == 'E' || s.charAt(index) == 'e')) {
index++;
//指数部分
//e或E的两边都要有数字,所以用&&
numeric = numeric && scanInteger(s);
}
//跳过尾部空格
while(s.charAt(index) == ' ')
index++;
return numeric && s.charAt(index) == '|' ;
}
}
作者:SunChonggao
链接:https://leetcode-cn.com/problems/biao-shi-shu-zhi-de-zi-fu-chuan-lcof/solution/zui-jian-dan-si-lu-xiang-xi-zhu-shi-zheng-shu-xiao/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。