46惰蜜、字符流中第一個不重復的字符
用字典計數昂拂,然后遍歷列表,得到第一個value為1的字符
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.temp = []
# 返回對應char
def FirstAppearingOnce(self):
# write code here
dic = {}
for i in self.temp:
dic[i] = dic.get(i, 0) + 1
for i in self.temp:
if dic[i] == 1:
return i
else:
return '#'
def Insert(self, char):
# write code here
self.temp.append(char)
47抛猖、替換空格
可以直接用re模塊寫格侯,或者先用空格split再用'%20'join
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
temp = s.split(' ')
return '%20'.join(temp)
48、矩陣中的路徑
題目看著挺難的财著,但是只要不停判斷下一個字符是否在上一個字符的上下左右四個地方就可以了联四,因此可以用遞歸實現。還要注意的是一個字符只能出現一次撑教。只需要把走過的路徑上的字符改成一個其它的字符就可以了朝墩。
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
for i in range(rows):
for j in range(cols):
if matrix[i*cols + j] == path[0]:
if self.find_path(list(matrix), rows, \
cols, path[1:], i, j):
return True
def find_path(self, matrix, rows, cols, path, i, j):
if not path:
return True
matrix[i*cols + j] = 0
if j+1 < cols and matrix[i*cols+j+1] == path[0]:
return self.find_path(matrix, rows, cols, path[1:], i, j+1)
elif j-1 >= 0 and matrix[i*cols+j-1] == path[0]:
return self.find_path(matrix, rows, cols, path[1:], i, j-1)
elif i+1 < rows and matrix[(i+1)*cols+j] == path[0]:
return self.find_path(matrix, rows, cols, path[1:], i+1, j)
elif i-1 >= 0 and matrix[(i-1)*cols+j] == path[0]:
return self.find_path(matrix, rows, cols, path[1:], i-1, j)
else:
return False
49、機器人的運動范圍
可以用廣度遍歷二叉樹的思路驮履。將走過的格子存入隊列鱼辙,然后不斷的pop和append。要注意的一點是不能走重復的格子玫镐。
代碼有點長倒戏,而且用了個列表保存走過的格子。
# -*- coding:utf-8 -*-
class Solution:
def movingCount(self, threshold, rows, cols):
# write code here
def istruepos(pos, threshold, rows, cols):
if 0<=pos[0]<=rows and 0<=pos[1]<=cols:
temp = sum([int(x) for x in str(pos[0])]) + sum([int(x) for x in str(pos[1])])
if temp<=threshold:
return True
return False
if rows==0 or cols==0 or threshold<0:
return 0
queue = [[0, 0]]
memory = [[0, 0]]
rst = 1
while queue:
i = queue.pop(0)
if istruepos([i[0], i[1]+1], threshold, rows-1, cols-1) and [i[0], i[1]+1] not in memory:
queue.append([i[0], i[1]+1])
memory.append([i[0], i[1]+1])
rst += 1
if istruepos([i[0], i[1]-1], threshold, rows-1, cols-1) and [i[0], i[1]-1] not in memory:
queue.append([i[0], i[1]-1])
memory.append([i[0], i[1]-1])
rst += 1
if istruepos([i[0]+1, i[1]], threshold, rows-1, cols-1) and [i[0]+1, i[1]] not in memory:
queue.append([i[0]+1, i[1]])
memory.append([i[0]+1, i[1]])
rst += 1
if istruepos([i[0]-1, i[1]], threshold, rows-1, cols-1) and [i[0]-1, i[1]] not in memory:
queue.append([i[0]-1, i[1]])
memory.append([i[0]-1, i[1]])
rst += 1
return rst
50恐似、求1+2+3+...+n
由于不能用條件判斷和乘除法杜跷,只能想到遞歸
# -*- coding:utf-8 -*-
class Solution:
def Sum_Solution(self, n):
# write code here
if n == 1:
return 1
return n+self.Sum_Solution(n-1)