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)
网友评论