【牛客】剑指offer部分编程题(持续更新......)
一、替换空格
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
return s.replace(' ', '%20')
二、最小K个数
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
# write code here
num = list(tinput)
num.sort()
if k <= len(num):
out = num[0:k]
else:
out = []
return out
三、第一个只出现一次的字符
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1.
import re
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
s = re.findall(r'[A-Za-z]+', s)
if len(s) == 0:
loc = -1
else:
s = s[0]
s = ','.join(s)
s = s.split(',')
count_dict = {}
j = 0
for i in s:
count_dict[i] = s.count(i)
if s.count(i) == 1:
loc = j
break
else:
loc = -1
j += 1
return loc
四、数组中只出现一次的数字
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
class Solution:
# 返回[a,b] 其中ab是出现一次的两个数字
def FindNumsAppearOnce(self, array):
# write code here
num_dict = {}
array = list(array)
num =[]
for i in array:
if array.count(i) == 1:
num.append(i)
if len(num) == 2:
break
return num
class Solution:
# 返回[a,b] 其中ab是出现一次的两个数字
def FindNumsAppearOnce(self, array):
# write code here
num = []
for i in array:
if i in num:
num.remove(i)
else:
num.append(i)
return num