【牛客】剑指offer部分编程题(持续更新......)

【牛客】剑指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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值