本周题目难度'Hard',但难的是思路,总结出了思路此题就豁然开朗了,使用语言'C'
题目:验证给定的字符串是否为数字。eg:"0" => true," 0.1 " => true,"abc" => false,"1 a" => false,"2e10" => true
思路:一个字符串去掉前后的空格(题目认为前后的空格可以无视),只需要考虑0-9、.、e、正负号这四种情况:1.一个字符串不包含0-9肯定判定为false;2.e最多只能出现一次,后面只能是0-9或正负号,并且后面必须再出现0-9;3.小数点.最多只能出现一次,并且后面只能是0-9或e;4.正负号最多只能出现两次,并且正负号的前面只能是e(或空格)。总结出需求来,代码就是EASY级别的,由于简单,我就不写注释了:
bool isNumber(char* s) {
int length = strlen(s);
int start = 0,end = length-1;
for (int i = 0; i < length; i++) {
start = I;
if (s[i] != ' ') break;
}
for (int i = length-1; i >= start; i--) {
if ((s[i] < '0' || s[i] > '9') && s[i] != '.' && s[i] != ' ') return false;
end = I;
if (s[i] != ' ') break;
}
int isContainE = 0,isContainDot = 0,isContainNum = 0,isContainSymbol = 0;
for (int i = start; i <= end; i++) {
if (s[i] >= '0' && s[i] <= '9') isContainNum = 1;
else if (s[i] == 'e' && isContainE == 0 && isContainNum) {
if (i+1 <= end) {
if ((s[i+1] < '0' || s[i+1] > '9') && s[i+1] != '+' && s[i+1] != '-') return false;
}
isContainE = 1;
isContainNum = 0;
}else if (s[i] == '.' && isContainDot == 0 && isContainE == 0) {
if (i+1 <= end) {
if ((s[i+1] < '0' || s[i+1] > '9') && s[i+1] != 'e' ) return false;
}
isContainDot = 1;
}else if ((s[i] == '+' || s[i] == '-') && isContainSymbol < 2) {
if ((isContainNum || isContainSymbol || isContainDot || isContainE) && s[i-1] != 'e') return false;
isContainSymbol++;
}else return false;
}
return isContainNum;
}
效率很好。