很麻烦的题目。首先列出各种情况。
1.首尾空格;
2.+-
3.e
4.出现其他字符和空格
但还是经不住很多小细节:
"1."
"."
"+.1"
"+1."
"2e.3"
"1e"
但我觉得我的思路一开始是对的,就是先按照e分开,按照.分开,然后左右分别处理。只是后来发现左右不能用同样的方法处理。
不过这哥们的状态boolean方法自然是最好,只需扫描一遍:http://blog.unieagle.net/2012/11/06/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Avalid-number/
public class Solution { public boolean isNumber(String s) { // Start typing your Java solution below // DO NOT write main() function if (s == null) return false; s = s.trim(); // removing empty spaces on two sides; int len = s.length(); if (len == 0) return false; boolean hasE = false; int eIndex = -1; for (int i = 0; i < len; i++) { if (s.charAt(i) == 'e' || s.charAt(i) == 'E') { if (hasE) return false; else { hasE = true; eIndex = i; } } } if (hasE) { String s1 = s.substring(0, eIndex); String s2 = s.substring(eIndex+1); return isNumberWithoutE(s1) && isSignedNumber(s2); } else { return isNumberWithoutE(s); } } private boolean isNumberWithoutE(String s) { int len = s.length(); if (len == 0) return false; int start = 0; if (s.charAt(0) == '+' || s.charAt(0) == '-') start++; if (start == len) return false; s = s.substring(start); len = s.length(); boolean hasDot = false; int dotIndex = -1; for (int i = 0; i < len; i++) { if (s.charAt(i) == '.') { if (hasDot) return false; else { hasDot = true; dotIndex = i; } } } if (hasDot) { String s1 = s.substring(0, dotIndex); String s2 = s.substring(dotIndex+1); if (s1.length() == 0 && s2.length() == 0) return false; if (s1.length() == 0) return isPureNumber(s2); if (s2.length() == 0) return isPureNumber(s1); return isPureNumber(s1) && isPureNumber(s2); } else { if (s.length() == 0) return false; return isPureNumber(s); } } private boolean isSignedNumber(String s) { int len = s.length(); if (len == 0) return false; int start = 0; if (s.charAt(0) == '+' || s.charAt(0) == '-') start++; if (start == len) return false; s = s.substring(start); return isPureNumber(s); } private boolean isPureNumber(String s) { int len = s.length(); if (len == 0) return false;; for (int i = 0; i < len; i++) { char c = s.charAt(i); if (c >= '0' && c <= '9') continue; else { return false; } } return true; } }