题解 | #表示数值的字符串#
表示数值的字符串
http://www.nowcoder.com/practice/e69148f8528c4039ad89bb2546fd4ff8
剑指offer思想,挺简单的思路
使用两个函数
findUnsignedInt() 查找无符号整数(不带正负号)
findInt() 查找有符号整数
整体数值可以表示为 D[A].[B]e/E[C]D
D表示空格,首先去掉起始空格
A为开始,可以没有,如果有可以是有符号数或者无符号,因此使用findInt
B部分,为小数点后面的部分,必须是无符号整数,小数可以没有整数部分不如".33"(但是此时小数点后面必须有无符号数) ,小数点后面可以没有数字,如"3."(此时前面必须有数字)因此不能是".",所以使用findUnsignedInt()||numeric
C部分,E、e后面的部分,必须为整数(可以为有符号),且前面必须有数字,后面必须有整数 numeric&&findInt()
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param str string字符串 * @return bool布尔型 */ bool isNumeric(string &str) { // write code here //首先找./e 之前的 if(str.empty()) return false; int pos = 0; //处理空格 while(str[pos]!='\0'&&str[pos]==' ') { ++pos; } //分为ABC三部分 A[.B][EC]; //A部分为Int类型 可以有正负号 //B部分为小数点后面的部分,必须为无符号整数,当然小数点前后可以没有数字 所以用|| //C部分为E、e部分,必须为有符号整数,即正整数。且前后必须都有整数 && bool numeric = findInt(str,pos); if(str[pos]=='.') { ++pos; numeric = findUnsignedInt(str,pos) || numeric; } if(str[pos]=='E' ||str[pos]=='e') { ++pos; numeric = numeric && findInt(str, pos); } while(str[pos]!='\0'&&str[pos]==' ') { ++pos; } return numeric&&str[pos]=='\0'; } //小数点后面部分 bool findUnsignedInt(string &str,int &pos) { //返回最后一个不是 int before = pos; while(str[pos]!='\0' && str[pos]>='0' && str[pos]<='9') { ++pos; } return pos>before; } bool findInt(string &str,int &start) { if(str[start]=='-' || str[start]=='+') { ++start; } return findUnsignedInt(str, start); } };