[leetcode]Valid Number
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.
算法思路:
排除法:遇到所有非法情况则返回false,扫描完之后返回true
非法情况:
符号:+、-最多只能出现两次,而且第二次必须出现在e/E后面。而且第一个+/-号之前必须没有数字,第二个比如紧接在e后面,而且后面必须有数字;
e:最多只能出现一次。而且前后必须有数字;
. : 最多只能出现一次,而且不能出现在e后面,.如果在字符串最后一位时,前面必须要有数字;
【提交出错后补充】第一次提交的时候,“e”报错,边界情况没有考虑真是不应该
总之这种题,不难,但是繁琐:
给出我出错的case,希望大家借鉴:(好多啊,囧)
005047e+6 true
3. true
.1 true
-. false
6+1 false
. 1 false
0e false
代码如下:
1 public class Solution { 2 public boolean isNumber(String s) { 3 if(s == null || s.trim().length() == 0) return false; 4 s = s.trim(); 5 char[] charArray = {'0','1','2','3','4','5','6','7','8','9','.','e','E','+','-'}; 6 Set<Character> set = new HashSet<Character>(); 7 for(char c : charArray){ 8 set.add(c); 9 } 10 boolean hasE = false, hasPoint = false, hasNum = false; 11 int operaterCount = 0; 12 for(int i = 0; i < s.length(); i++){ 13 if(!set.contains(s.charAt(i))) return false; 14 if(s.charAt(i) <= '9' && s.charAt(i) >= '0') hasNum = true; 15 if(s.charAt(i) == 'E' || s.charAt(i) == 'e'){ 16 if(i == 0 || i == s.length() - 1) return false; 17 if(!hasE && hasNum) hasE = true; 18 else return false; 19 } 20 if(s.charAt(i) == '.'){ 21 if(i == 0 && 1 == s.length()) return false; 22 if(i == s.length() - 1 && !hasNum) return false; 23 if(!hasPoint && !hasE) hasPoint = true; 24 else return false; 25 } 26 if(s.charAt(i) == '-' || s.charAt(i) == '+'){ 27 if(i == s.length() - 1 || (i != 0 && s.charAt(i - 1) != 'e' && s.charAt(i - 1) != 'E')) return false; 28 if(operaterCount == 2) return false; 29 if(operaterCount == 1 && !hasE && !hasNum) return false; 30 operaterCount++; 31 } 32 } 33 return true; 34 } 35 }