The idea is to loop the entire String, to exclude all possible bad cases or keep only good cases, either way would work. Just there are a lot of rules for clarification, that is the hard point to catch all.
The work below use special mark for bad cases detector, like decimal point, e mark or operators.
public class Solution {
public boolean isNumber(String s) {
s = s.trim();
if(s == null || s.length() == 0){
return false;
}
if(s.charAt(0) == '.' && s.length() == 1){
return false;
}
// if(s.charAt(0) == '0' && s.length() > 1){ //e? and what about '.1' valid?
// return false;
// }
if(s.charAt(0) == 'e'){
return false;
}
int decimalCount = 0;
int eCount = 0;
int index = 0;
while(index < s.length()){
if(!((s.charAt(index) >= '0' && s.charAt(index) <= '9') || s.charAt(index) == 'e' || s.charAt(index) == '.' || (index == 0 && (s.charAt(index) == '+' || s.charAt(index) == '-')) || (index > 0 && s.charAt(index - 1) == 'e' && (s.charAt(index) == '+' || s.charAt(index) == '-')))){
return false;
}
if(s.charAt(index) == '.'){
decimalCount++;
if(decimalCount > 1){
return false;
}
if(eCount > 0){
return false;
}
if(index > 0 && (s.charAt(index - 1) == 'e' || ((s.charAt(index - 1) == '+' || s.charAt(index - 1) == '-') && index == s.length() - 1))){
return false;
}
// if(index == s.length() - 1){
// return false;
// }
}
if(s.charAt(index) == 'e'){
eCount++;
if(eCount > 1 || index == s.length() - 1){
return false;//?
}
if(index > 0 && s.charAt(index - 1) == '.' && index - 1 == 0){
return false;
}
if(s.charAt(index) == 'e' && (s.charAt(index - 1) == '+' || s.charAt(index - 1) == '-') && index == 1){
return false;
}
}
if((s.charAt(index) == '+' || s.charAt(index) == '-') && index == s.length() - 1){
return false;
}
index++;
}
return true;
}
}
没有评论:
发表评论