第2章 面试需要的基础知识
第3章 高质量的代码
面试题16:数值的整数次方
面试题20:表示数值的字符串
面试题21:调整数组顺序使奇数位于偶数前面
面试题22:链表中倒数第k个结点
面试题23 :链表中环的入口
面试题24 :翻转链表
第4章 解决面试题的思路
第5章 优化时间和空间效率
第6章 面试中的各项能力
第7章 两个面试案例
题目描述
牛客网
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100",“5e2”,"-123",“3.1416"和”-1E-16"都表示数值。 但是"12e",“1a3.14”,“1.2.3”,"±5"和"12e+4.3"都不是。
解题思路
题目难度不大,就是要考虑全面。书上的那一套感觉还不如自己分析来得快。
这里我们以e,E为划分点,e之前的数字可以包括0-9,+,-,’.’。e之后的数字不能包含小数点,还有0不能开头,除非其后接小数点;小数点可以开头,符号一定要位于开头。考虑清楚这几种情况就可以了。还要注意一点就是不能有两个小数点。
实战
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
if s == '0':
return True
if not s:
return False
def e_later(string):
if not string:
return False
for i, ch in enumerate(string):
if (ch == '+' or ch == '-') and i != 0:
return False
if ch == '0' and i == 0:
return False
if (ch < '0' or ch > '9') and ch != '+' and ch != '-':
return False
return True
if len(s.split('.')) > 2: # 只能有一个小数点
return False
for i, ch in enumerate(s):
if (ch == '+' or ch == '-') and i != 0:
return False
if ch == '0' and i == 0 and len(s) > 1 and s[1] != '.':
return False
if ch == 'e' or ch == 'E':
return e_later(s[i+1:])
if (ch < '0' or ch > '9') and ch != '.' and ch != '+' and ch != '-':
return False
return True