Difficulty: Hard

 More:【目录】LeetCode Java实现

Description

Validate if a given string can be interpreted as a decimal number.

Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
" -90e3   " => true
" 1e" => false
"e3" => false
" 6e-1" => true
" 99e2.5 " => false
"53.5e93" => true
" --6 " => false
"-+3" => false
"95a54e53" => false

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number:

  • Numbers 0-9
  • Exponent - "e" or "E"
  • Positive/negative sign - "+"/"-"
  • Decimal point - "."

Of course, the context of these characters also matters in the input.

Intuition

Method1: A valid number is in the form of A.B e/E A (A: integer, B: unsigned integer), so it is helpful to break the problem down to several components that can be solved individually. Detailed solution refer to: 表示数值的字符串

 Method2: Use some flags(eSeen, pointSeen, isNum) while scan each character in the String. The solution is shown below.

Solution

    public boolean isNumber(String s) {
if(s==null || s.length()<=0)
return false;
s=s.trim();
boolean isNum=false;
boolean pointSeen=false;
boolean eSeen=false;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='+'||s.charAt(i)=='-'){
if(i!=0 && s.charAt(i-1)!='e' && s.charAt(i-1)!='E')
return false;
}else if(Character.isDigit(s.charAt(i))){
isNum=true;
}else if(s.charAt(i)=='.'){
if(eSeen || pointSeen)
return false;
pointSeen=true;
}else if(s.charAt(i)=='e' || s.charAt(i)=='E' ){
if(eSeen || !isNum)
return false;
eSeen=true;
isNum=false;
}else
return false;
}
return isNum;
}

  

Complexity

Time complexity : O(n)

Space complexity :  O(1)

What I've learned

1. Ought to make the best of flags. Learn to use flags well.

 More:【目录】LeetCode Java实现

最新文章

  1. python 入门学习之环境搭载
  2. NProgress.js template
  3. (转)Ehcache 整合Spring 使用页面、对象缓存
  4. Android课程---Activity 的生命周期
  5. Dynamic CRM 2013学习笔记(三十八)流程1 - 操作(action)开发与配置详解
  6. Maven运行时异常java.lang.UnsupportedClassVersionError的解决方案
  7. JS 去字符串空格 总结
  8. 【GDI+】一些规则多边形分离的问题
  9. Python基础教程【读书笔记】 - 2016/7/5
  10. Maven使用本地jar包(小私服?支持自动打入war包)
  11. 相比于python2.6,python3.0的新特性。
  12. 关于NIOS ii烧写的几种方式(转)
  13. Java面向对象 集合(下)
  14. 在ubuntu中屏蔽“检测到系统程序出现问题”对话框
  15. 【转载】vi/vim使用进阶: 指随意动,移动如飞 (二)
  16. 微信WebView关闭后本地cookie无法清除问题
  17. Linq to Sharepoint--如何获取Linq Query 生成的CALM
  18. 小课堂week16 编程范式巡礼第一季 三大基石
  19. ant font 本地化
  20. (九)jsMath

热门文章

  1. POJ 1797 Heavy Transportation / SCU 1819 Heavy Transportation (图论,最短路径)
  2. java 7 升级后,控制面板里找不到java图标了
  3. Python正则表达式(regular expression)简介-re模块
  4. Intellij IDEA导入web项目详解(解决访问的404)
  5. [iOS]@synthesize和@dynamic关键字
  6. JavaScript继承详解(三)
  7. PB程序调用C++ COM生成对象发回-2问题
  8. lemon spj无效编译器解决方法
  9. DVWA的Xss跨站总结
  10. JVM 垃圾回收算法及案例分析