算法之美-每周打卡(URL化&重新排列字符串)

第一周练习内容:

1.面试题 01.03. URL化
   编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增 字符,并且知道字符串的“真实”长度。

(注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作)

输入实例

题目来自leetcode


python代码如下:


class Solution:
    def replaceSpaces(self, S: str, length: int) -> str:
        new_string = ''
        for s in S:
            # print(s, end='')
            if s == ' ':
                s = '%20'
            if length == 0:
                break
            new_string += s
            length -= 1
        #     print(new_string)
        # print(len(new_string))
        return new_string


String = "               "
long = 5
print(Solution().replaceSpaces(String, long))

代码执行后:

在这里插入图片描述

时间执行上还是有很大问题,过后思考新方案,再进行优化(此处做标记)


2.重新排列字符串(No.1528)

    给你一个字符串 s 和一个长度相同的整数数组 indices 。 请你重新排列字符串 s ,其中第 i 个字符需要移动到 indices[i] 指示的位置。 返回重新排列后的字符串。 字符,并且知道字符串的“真实”长度。

leetcode

题目来自leetcode


python代码如下:

class Solution:
    # 方法1
    def trian_one(self, s, slist):
        new_dict = {}
        for i in range(len(slist)):
            new_dict[slist[i]] = s[i]
        print(new_dict)
        res = ''
        for j in range(len(slist)):
            res += ''.join(new_dict[j])
        return res

    # 方法2
    def t_list(self, s, slist):
        result = list(s)
        print(result)
        for v in range(len(slist)):
            result[slist[v]] = s[v]
        return ''.join(result)


indices = [4, 5, 6, 7, 0, 2, 1, 3]
s = "codeleet"
print(Solution().trian_one(s, indices))
print(Solution().t_list(s, indices))

代码执行后:

方法2执行结果:

在这里插入图片描述


总结

了解并熟悉LeetCode习题:
简单应用了一些基本语法和循环逻辑

  • 本周两题任务完成
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值