题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串”+100”,”5e2”,”-123”,”3.1416”和”-1E-16”都表示数值。 但是”12e”,”1a3.14”,”1.2.3”,”+-5”和”12e+4.3”都不是。
这道题不难,但是超级麻烦。这个和正则表达式一样,肯定得用递归的手段。
(1)首先判断第一位是不是符号位,在一般的数中,符号位不能出现两次,index+1;
(2)如果是整数,index+1,继续判断下一位;
(3)如果是小数点,继续下一位,但是之后不能再有小数点;
(4)如果是除e/E以外字母,false;
(5)如果是E/e,写一个新函数,判断e之后的是不是一个标准的整数(此时不能有小数点,应该可以整合这两个函数,不过感觉没必要);
(6)这个新函数,只能是整数,不能是小数。
推荐不适用递归的写法
注意:递归的出口是if(index == str.length) return true;
,所以char ch = str[index];
一定要写在它的后面,否则会发生越界问题。
最好把0-9的判断提前,减少运算次数。
public class Solution {
public boolean isZhengshuNext(char[] str,int index,boolean haveZF2){
if(index == str.length)
return true;
char ch = str[index];
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
return false;
if(haveZF2 && (ch == '+' || ch == '-'))
return false;
if(ch >= '0' && ch <= '9')
return isZhengshuNext(str,index+1,haveZF2);
if(ch == '.'){
return false;
}
return false;
}
public boolean _isNumeric(char[] str,int index,boolean haveZF,boolean havePoint) {
if(index == str.length)
return true;
char ch = str[index];
if(ch >= '0' && ch <= '9')
return _isNumeric(str,index+1,haveZF,havePoint);
if(haveZF && (ch == '+' || ch == '-'))
return false;
if(!havePoint && ch == '.'){
havePoint = true;
return _isNumeric(str,index+1,haveZF,havePoint);
}
if(havePoint && ch == '.')
return false;
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
if(ch == 'e' || ch == 'E'){
boolean haveZF2 = true;
if(index + 1 < str.length){
if((str[index+1] == '+' || str[index+1] == '-'))
return isZhengshuNext(str,index+2,haveZF);
return isZhengshuNext(str,index+1,haveZF);
}
}
return false;
}
return false;
}
public boolean isNumeric(char[] str) {
boolean haveZF = false;
boolean havePoint = false;
int index = 0;
if(str[index] == '+' || str[index] == '-'){
haveZF = true;
return _isNumeric(str,index+1,haveZF,havePoint);
}
return _isNumeric(str,index,haveZF,havePoint);
}
}
不过,看了别人的做法,我也是醉了:
其实我的做法复杂了,考虑的也多了。E后面只需要判断是不是一个整数就可以了。
而且,一个循环也可以解决。
public class Solution {
public boolean isNumeric(char[] str) {
String s=String.valueOf(str);
return s.matches("[+-]?[0-9]*(\\.[0-9]*)?([eE][+-]?[0-9]+)?");
}
}
不使用递归:
public class Solution {
public boolean isExponential(char[] str,int index){
for(int i=index;i<str.length;i++){
char ch = str[index];
if(ch >= '0' && ch <= '9'){
index++;
continue;
}
if(str[index] == '+' || str[index] == '-')
index++;
if(ch == '.')
return false;
}
return true;
}
public boolean isNumeric(char[] str) {
int index = 0;
boolean havePoint = false;
if(str[index] == '+' || str[index] == '-')
index++;
for(int i=index;i<str.length;i++){
char ch = str[index];
if(i > 0 && (ch == '+' || ch == '-')){
return false;
}
if(ch >= '0' && ch <= '9'){
index++;
continue;
}
if(ch == '.'){
if(havePoint)
return false;
index++;
havePoint = true;
continue;
}
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
if(ch == 'e' || ch == 'E'){
if(index + 1 < str.length)
return isExponential(str,index+1);
else
return false;
}
return false;
}
}
return true;
}
}