【LeetCode】65. Valid Number
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实现
最新文章
- python 入门学习之环境搭载
- NProgress.js template
- (转)Ehcache 整合Spring 使用页面、对象缓存
- Android课程---Activity 的生命周期
- Dynamic CRM 2013学习笔记(三十八)流程1 - 操作(action)开发与配置详解
- Maven运行时异常java.lang.UnsupportedClassVersionError的解决方案
- JS 去字符串空格 总结
- 【GDI+】一些规则多边形分离的问题
- Python基础教程【读书笔记】 - 2016/7/5
- Maven使用本地jar包(小私服?支持自动打入war包)
- 相比于python2.6,python3.0的新特性。
- 关于NIOS ii烧写的几种方式(转)
- Java面向对象 集合(下)
- 在ubuntu中屏蔽“检测到系统程序出现问题”对话框
- 【转载】vi/vim使用进阶: 指随意动,移动如飞 (二)
- 微信WebView关闭后本地cookie无法清除问题
- Linq to Sharepoint--如何获取Linq Query 生成的CALM
- 小课堂week16 编程范式巡礼第一季 三大基石
- ant font 本地化
- (九)jsMath
热门文章
- POJ 1797 Heavy Transportation / SCU 1819 Heavy Transportation (图论,最短路径)
- java 7 升级后,控制面板里找不到java图标了
- Python正则表达式(regular expression)简介-re模块
- Intellij IDEA导入web项目详解(解决访问的404)
- [iOS]@synthesize和@dynamic关键字
- JavaScript继承详解(三)
- PB程序调用C++ COM生成对象发回-2问题
- lemon spj无效编译器解决方法
- DVWA的Xss跨站总结
- JVM 垃圾回收算法及案例分析