1. 表示数值的字符串
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
解:
思考方向应该是把非法的情况列举出来,合法的情况太多了。这题比较繁琐。
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
if not s:
return False
n = len(s)
sign, decimal, hasE = False, False, False
for i in range(n):
if s[i] in {‘e‘, ‘E‘}:
if i == n-1:
return False # e后面要接数字
if hasE:
return False # 不能有两个e
hasE = True
elif s[i] in {‘+‘, ‘-‘}:
if sign and s[i-1] not in {‘e‘, ‘E‘}: # 第二次出现+-,必须在e后面
return False
if not sign and i > 0 and s[i-1] not in {‘e‘, ‘E‘}: # 第一次出现+-,且不是开头,也必须在e后面
return False
sign = True
elif s[i] == ‘.‘:
if hasE or decimal: # e后面不能有小数点,小数点不能出现两次
return False
decimal = True
elif s[i] < ‘0‘ or s[i] > ‘9‘: # 非法字符
return False
return True
2. 字符流中第一个不重复的字符
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
解:
显然要用到哈希表。
class Solution:
# 返回对应char
def __init__(self):
self.strs = ‘‘
def FirstAppearingOnce(self):
# write code here
if not self.strs:
return ‘#‘
n = len(self.strs)
hashmap = dict()
for i in range(n):
count, index = hashmap.get(self.strs[i], (0, -1))
hashmap[self.strs[i]] = (count+1, i)
first_index = n
for key, value in hashmap.items():
if value[0] == 1:
first_index = min(first_index, value[1])
return ‘#‘ if first_index == n else self.strs[first_index]
def Insert(self, char):
# write code here
self.strs += char
3.替换空格
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
解:
递归实现
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
if not s:
return s
if s[0] == ‘ ‘:
return ‘%20‘ + self.replaceSpace(s[1:])
return s[0] + self.replaceSpace(s[1:])
扫一遍记录位置,然后挨个替换,注意替换过程中原先记录的索引会改变,要对应好。
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
if not s:
return s
tobeReplace = []
n = len(s)
for i in range(n):
if s[i] == ‘ ‘:
tobeReplace.append(i)
m = len(tobeReplace)
for j in range(m):
s = s[:tobeReplace[j]+2*j] + ‘%20‘ + s[tobeReplace[j]+2*j+1:]
return s
原文:https://www.cnblogs.com/chaojunwang-ml/p/11441094.html