题解 | #表示数值的字符串#
表示数值的字符串
https://www.nowcoder.com/practice/e69148f8528c4039ad89bb2546fd4ff8
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param str string字符串
* @return bool布尔型
*/
public boolean isNumeric (String str) {
// write code here
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;
}
}
解题思想:
* hashNum : 是否已经有数字
* hashE :是否已经有E
* hasSign :是否已经有符号
* hasDot :是否已经有⼩数点
* 本质是转态的切换,最最重要的⼀点,是 E 出现之后,其实⼩数点和符号,和数字,都是可以再出现的,可以理解为 E 就是⼀个分割线。
#算法##算法笔记#