一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github

欢迎大家关注我的新浪微博,我的新浪微博

欢迎转载,转载请注明出处

(一)题目

Validate if a given string is numeric.

Some examples:

“0” => true

” 0.1 ” => true

“abc” => false

“1 a” => false

“2e10” => true

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front >before implementing one.

Update (2015-02-10):

The signature of the C++ function had been updated. If you still see your function signature accepts a const >char * argument, please click the reload button to reset your code definition.

(二)解题

题目大意:判断一个string数是否为有效数

大致从以下三点考虑这个问题:

1、全为数字

2、存在有且仅有一个’e‘,这个时候需要判断前后的数字有效,如4e+,.e1

3、存在有些仅有一个’.’,注意指数不能为小数

做题时没有考虑到的特殊情况:

“e”,“4e+”,“.e1”

class Solution {
public:
    bool isNumber(string s) {
        int len = s.length();
        if(len == 0) return false;
        //剔除前面的空格
        int st = 0 ;
        while(st<len&&s[st] == ' ') st++;
        int ed = len-1;
        //剔除后面的空格
        while(ed>=0&&s[ed] == ' ') ed--;
        if(st>ed) return false;//如果全是空格就返回false
        //符号
        if(s[st]=='+'||s[st]=='-') st++;
        //标志.和e的位置
        int hase = -1;
        int hasdot =-1;
        //开始循环
        for(int i =st ; i <= ed ;)
        {
            if(s[i]>='0'&&s[i]<='9') i++;
            else if(s[i]=='e')
            {
                if(hase==-1) hase = i;//只能出现一个e
                else return false;
                if(i==st||i==ed) return false;//e在最前面或最后面返回false
                i++;
                if(s[i]=='+'||s[i]=='-') i++;//考虑指数带有符号
                if(i>ed) return false;//指数非法,如10e+
            }
            else if(s[i]=='.')
            {
                if(hasdot==-1) hasdot = i;//只能有一个.
                else return false;
                i++;
                if(ed-st==0) return false;//string为“.”的特殊情况
            }
            else return false;
        }
        if(hase!=-1&&hasdot!=-1){//判断e前面的数字有效
            if(hase<hasdot) return  false;//指数不能为小数
            if(hasdot==st&&hase-hasdot==1) return false;//“.e1”的特殊情况,e前面数要有效
        }
        return true;
    }
};

最新文章

  1. http status 301/302 &amp; java重定向/转发
  2. Ajax发送POST请求SpringMVC页面跳转失败
  3. npm 安装不了模块
  4. ASP.NET 学习记录之一
  5. 【Spring开发】—— Spring注入静态变量
  6. dubbo源码之二——dubbo入口
  7. 家业兴衰说传承(cc)
  8. SQLite数据库管理的相关命令
  9. 微软开放技术(中国)携 CKAN 和 OData 技术引入基于 Azure 的开放数据平台
  10. hadoop 1 testcase运行方法
  11. [JWFD开源工作流]JWFD开源工作流官方下载内容更新
  12. 乱译文档--开始使用Musca
  13. DNS解析详细过程
  14. Dev 甘特图
  15. Python学习笔记之运算符之一
  16. QPS/TPS/并发量/系统吞吐量概念和公式
  17. 【转】JS中setTimeout和setInterval的最大延时值详解
  18. 【iCore1S 双核心板_ARM】例程二十:UART_IAP_ARM实验——更新升级STM32
  19. Spring3(一) 控制反转(IoC)和依赖注入(DI)
  20. Java中的枚举Enum

热门文章

  1. centos 6安装 H3C iNode 上网客户端
  2. C++/C# 开发高级案例资料一次送!关注加群领取哦!
  3. SAS中常见的数组函数
  4. python序列化pickle/cPickle
  5. python 循环和file操作实现用户密码输错三次将用户锁定
  6. C语言多维数组的指针传递
  7. Python 元组内置函数
  8. JMETER_从入门到放弃系列
  9. Bootstrap3 表单-被支持的控件:输入框
  10. Java对象的创建 —— new之后JVM都做了什么?