Leetcode 65. Valid Number 验证数字 解题报告
来源:互联网 发布:淘宝苹果手机 编辑:程序博客网 时间:2024/05/21 06:37
1 解题思想
更新下:这道突然就很多访问,想起来好像是lt提交通过率最低的,嗯,我写的也不是特别详细,如有问题可以新浪微博@MebiuW交流~~
这道题条条框框是在太多了,各种情况。。不过简略来说,正确的做法应该是:
1、熟悉数字的表述规则(可以看网上的,也可以看我代码的),这道题关键是要懂所有的数字规则。
2、对输入的数字首先进行必要的检测,是否有abc或者中间空格等非法字符
3、将e前面和e后面分开计算!e前面允许有小数点形式的,e后面不允许有小数点形式的
4、数字的形式一般是 可以有正负号,如果是0.几,可以省略0,“.”前面不一定有数字,点后面一定有数字。。等等
2 原题
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.
3 AC解
public class Solution { public boolean check(String tmp,boolean point){ //为空的情况肯定失败 if(tmp.length()<1) return false; char chars[]=tmp.toCharArray(); int i=0; boolean num=false; //是否存在符号,十号的话要先跳过,且只能有一个。。如果符号过后就没有数字了,那么也是非法的 if(chars[i]=='+' || chars[i]=='-') i++; if(i==chars.length) return false; //整数位置的数据 while(i<chars.length && chars[i]<='9' && chars[i]>='0'){ i++; num=true; } //如果不允许出现小数点,那么这个过程就必须匹配结束,不然就是失败 if(i<chars.length && point==false) return false; //允许小数点,下一位必须为小数点 if(i<chars.length && chars[i]=='.'){//小数点后,必须遇到e或结束 boolean num2=false; i++; while(i<chars.length && chars[i]<='9' && chars[i]>='0'){ i++; num2=true; } //小数点前要有数字,小数点后也要有数字,至少成立一个 if(num2==false && num==false) return false; } return i==chars.length; } public boolean isNumber(String s) { //去除空格 while(s.startsWith(" ")) s=s.substring(1); while(s.endsWith(" ")) s=s.substring(0,s.length()-1); if(s.length()<1) return false; //e的后面不允许小数点,前面允许 所以如果有e就拆分运算 if(s.indexOf('e')==-1) return check(s,true); else return check(s.substring(0,s.indexOf('e')),true) &&check(s.substring(s.indexOf('e')+1),false) ; } public static void main(String args[]){ Solution s=new Solution(); System.out.println(s.isNumber(". 1")); }}
- Leetcode 65. Valid Number 验证数字 解题报告
- [leetcode] 65. Valid Number 解题报告
- [Leetcode] 65. Valid Number 解题报告
- 【LeetCode】Valid Number 解题报告
- 【LeetCode】611.Valid Triangle Number解题报告
- Leetcode #36. Valid Sudoku 数独游戏验证 解题报告
- Leetcode 125. Valid Palindrome 回文验证 解题报告
- leetCode 65.Valid Number (有效数字)
- LeetCode 65. Valid Number(校验数字)
- LeetCode解题报告--Valid Parentheses
- [LeetCode] Valid Parentheses 解题报告
- [LeetCode] Valid Sudoku 解题报告
- 【LeetCode】Valid Anagram 解题报告
- [LeetCode] Valid Parentheses 解题报告
- 【LeetCode】Valid Parentheses 解题报告
- Leetcode Valid Parentheses 解题报告
- [LeetCode]Valid Number有效数字
- [LeetCode]Palindrome Number,解题报告
- Binder学习笔记(一)
- C++作业5
- Overall Comparision With WCDMA
- JavaScript 函数的执行过程
- CUDA学习笔记九
- Leetcode 65. Valid Number 验证数字 解题报告
- git和gitHub使用
- c++作业五—数组
- 关于protected权限
- Linux学习之权限管理命令
- 文件读取权限
- __weak与__block修饰符到底有什么区别
- POJ 1509 Glass Beads【字符串最小表示法】
- 【LeetCode】Pascal's Triangle II 解题报告