leetcode - Valid Number
2015-06-10 11:07
369 查看
题目:
Valid Number
Validate if a given string is numeric.
Some examples:
Valid Number
Validate if a given string is numeric.
Some examples:
"0"=>
true
" 0.1 "=>
true
"abc"=>
false
"1 a"=>
false
"2e10"=>
true
class Solution { public: bool isNumber(string s) { if (s.empty()) return false; //删除开头和结尾的空格 //删除开头空格 if (s[0] == ' ') { int i = 1; while (i<s.size() && s[i] == ' ') ++i; s.erase(s.begin(), s.begin() + i); } //删完开头空格后若为空,则返回假 if (s.empty()) return false; int size = s.size(); //删除结尾空格 if (s[size - 1] == ' ') { int i = size - 2; while (i >= 0 && s[i] == ' ') --i; if (i<0) return false; s.erase(s.begin() + i + 1, s.end()); } //删除结尾空格后,若为空或以'e'开头,返回假 if (s.empty() || s[0] == 'e' || s[0] == 'E') return false; //若仍然有空格,返回假 if (s.find(" ") != string::npos) return false; size = s.size(); int index = 0; if (s[index] == '+' || s[index] == '-') ++index; //只有加减号,返回假 if (index == size) return false; //若第一个小数点前有数字,docbeforenum为真 bool docbeforenum = false; if (s[index] >= '0' && s[index] <= '9') docbeforenum = true; scanNumber(s, index); //一个整数,返回真 if (index == size) return true; bool res = true; //小数 if (s[index] == '.') { ++index; //'.'是字符串最后一位时,'.'前有数字则返回真,否则返回假 if (index == size) { return docbeforenum; } //'.'后紧跟着非数字时 if (s[index]<'0' || s[index]>'9') { if ((s[index] == 'e' || s[index] == 'E') && docbeforenum) { // “数字.e” 的形式,继续判断 } else return false; } scanNumber(s, index); //小数的形式,返回真 if (index == size) return true; if (s[index] == 'e' || s[index] == 'E') res = isExp(s, index); } else if (s[index] == 'e' || s[index] == 'E') { // 'e'前没有数字,返回假 if (docbeforenum == false) return false; res = isExp(s, index); } else res = false; return res && s[index] == '\0'; } //遇到数字则往后走 void scanNumber(const string &s, int &index) { int size = s.size(); while (index<size && s[index] >= '0' && s[index] <= '9') ++index; } //判断以'e'开头的字符串是否能代表指数 bool isExp(const string &s, int &index) { ++index; int size = s.size(); //只有一个'e',返回假 if (index == size) return false; if (s[index] == '+' || s[index] == '-') ++index; //'e'后没有数字,返回假 if (index == size || s[index]<'0' || s[index]>'9') return false; scanNumber(s, index); return true; } };
相关文章推荐
- 双目视觉测量的,极线匹配
- Bash shell的构成
- Ubuntu 14.04远程登录服务器--ssh的安装和配置
- php session 的应用
- 如何把PDF文件完整的转换到Excel中
- Android(java)学习笔记107-0:通过反射获得构造方法并且使用
- linux 命令行 I/O 重定向和管道
- VS2010开发程序打包详解
- 微信支付 V3版
- Android Studio 慢吗?No!!你还不懂她···
- 虚拟现实项目开发流程
- 约瑟夫环
- 使用Maven+Nexus+Jenkins+Svn+Tomcat+Sonar搭建持续集成环境(一)
- PHP array_intersect_ukey()
- Linux shell位置参数
- Android中的Selector的用法
- web.xml 中的listener、 filter、servlet 加载顺序及其详解
- shell 条件判断语句参数介绍
- MFC中自定义类访问主对话框控件
- Linux的Shell编程 Shell基本语法