详细见:leetcode.com/problems/valid-number
Java Solution: github
package leetcode;
public class P065_ValidNumber {
public static void main(String[] args) {
System.out.println(new Solution().isNumber(" 4e+ "));
}
/*
* 艰难的试错AC
* 4 ms
* 61.35%
*/
static class Solution {
public boolean isNumber(String s) {
char[] cs = s.toCharArray();
int sti = 0, eni = cs.length - 1;
while (sti <= eni && cs[sti] == ' ') sti ++;
while (eni >= sti && cs[eni] == ' ') eni --;
if (sti > eni)
return false;
if (sti <= eni && (cs[sti] == '-' || cs[sti] == '+'))
sti ++;
boolean isHasE = false, isHasDot = false, isHasNum = false;
int indexOfE = -1;
for (int i = sti; i <= eni; i ++) {
if (cs[i] == ' ')
return false;
if (cs[i] == 'e' || cs[i] == 'E') {
if (!isHasNum || isHasE || i == sti || i == eni)
return false;
isHasE = true;
indexOfE = i;
if (cs[i + 1] == '-' || cs[i + 1] == '+') {
if (i + 1 == sti)
return false;
i ++;
}
isHasNum = false;
continue;
}
if (cs[i] == '.') {
if (isHasDot)
return false;
isHasDot = true;
if (indexOfE != -1 && indexOfE < i)
return false;
continue;
}
if (! (cs[i] >= '0' && cs[i] <= '9'))
return false;
isHasNum = true;
}
return isHasNum;
}
}
}
C Solution: github
/*
url: leetcode.com/problems/valid-number
AC 6ms 11.86%
*/
typedef int bool;
/*
sign:
still sign means still true
1: num
2: e
3: dot
*/
bool isNumber(char* s) {
char c = '\0';
int sign = 0;
int dot_cnt = 0;
int e_cnt = 0;
int has_val = 0;
int si = 0, ei = -1, i = 0;
while (s[ei+1] != '\0') ei ++;
while (s[ei] == ' ') ei --;
while (s[si] == ' ') si ++;
for (i = si; i <= ei ; i++) {
c = s[i];
if (c == '\0') break;
if (c == '-' || c == '+') {
if (i != si && sign != 2)
return 0;
continue;
}
if (c == ' ') {
return 0;
}
//check .(dot)
if (c == '.') {
//has .(dot)
if (dot_cnt != 0) return 0;
if (sign == 2) return 0;
if (e_cnt > 0) return 0;
dot_cnt = 1;
sign = 3;
continue;
}
//check e
if (c == 'e' || c == 'E') {
//has e
if (e_cnt != 0) return 0;
if (has_val == 0) return 0;
e_cnt = 1;
sign = 2;
continue;
}
if (c >= '0' && c <= '9') {
has_val = 1;
sign = 1;
continue;
}
return 0;
}
return sign == 2 ? 0 : has_val;
}
int main() {
char* s = "-13. ";
printf("answer is %d\r\n", isNumber(s));
return 0;
}
Python Solution: github
#coding=utf-8
'''
url: leetcode.com/problems/valid-number
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年4月14日
@details: Solution: 56ms 86.13%
'''
class Solution(object):
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
try:
float(s)
return True
except:
return False