当前位置:网站首页>LeetCode简单题之计算字符串的数字和
LeetCode简单题之计算字符串的数字和
2022-04-23 07:02:00 【·星辰大海】
题目
给你一个由若干数字(0 - 9)组成的字符串 s ,和一个整数。
如果 s 的长度大于 k ,则可以执行一轮操作。在一轮操作中,需要完成以下工作:
将 s 拆分 成长度为 k 的若干 连续数字组 ,使得前 k 个字符都分在第一组,接下来的 k 个字符都分在第二组,依此类推。注意,最后一个数字组的长度可以小于 k 。
用表示每个数字组中所有数字之和的字符串来 替换 对应的数字组。例如,“346” 会替换为 “13” ,因为 3 + 4 + 6 = 13 。
合并 所有组以形成一个新字符串。如果新字符串的长度大于 k 则重复第一步。
返回在完成所有轮操作后的 s 。
示例 1:
输入:s = “11111222223”, k = 3
输出:“135”
解释:
- 第一轮,将 s 分成:“111”、“112”、“222” 和 “23” 。
接着,计算每一组的数字和:1 + 1 + 1 = 3、1 + 1 + 2 = 4、2 + 2 + 2 = 6 和 2 + 3 = 5 。
这样,s 在第一轮之后变成 “3” + “4” + “6” + “5” = “3465” 。 - 第二轮,将 s 分成:“346” 和 “5” 。
接着,计算每一组的数字和:3 + 4 + 6 = 13 、5 = 5 。
这样,s 在第二轮之后变成 “13” + “5” = “135” 。
现在,s.length <= k ,所以返回 “135” 作为答案。
示例 2:
输入:s = “00000000”, k = 3
输出:“000”
解释:
将 “000”, “000”, and “00”.
接着,计算每一组的数字和:0 + 0 + 0 = 0 、0 + 0 + 0 = 0 和 0 + 0 = 0 。
s 变为 “0” + “0” + “0” = “000” ,其长度等于 k ,所以返回 “000” 。
提示:
1 <= s.length <= 100
2 <= k <= 100
s 仅由数字(0 - 9)组成。
来源:力扣(LeetCode)
解题思路
这样的题目一看就非常能想到递归来试下。一眼就能看出可以递归的题目往往写法上比较简单,只需要符合第一个结果就能马上写出code。在每一层递归里做一个简单的事,就是将整个字符串先三个三个按照要求拼成一个新的字符串,至于新的字符串长度是什么情况无需关注,下一层自会解决。
class Solution:
def digitSum(self, s: str, k: int) -> str:
if len(s)<=k: #递归出口
return s
S,temp,count='','',0
for i in s:
temp+=i
count+=1
if count%k==0:
S+=str(sum([int(j) for j in temp]))
temp=''
if temp: #假如s的长度不是k的整数倍,处理尾巴
S+=str(sum([int(j) for j in temp]))
s=S
return self.digitSum(s,k)
版权声明
本文为[·星辰大海]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_18560985/article/details/124354034
边栏推荐
猜你喜欢
1216_MISRA_C规范学习笔记_控制流的规则要求
Intranet penetration series: icmptunnel of Intranet tunnel (Master James Barlow's)
Thinkphp6 + JWT realizes login verification
输入 “ net start mysql ”,出现 “ 发生系统错误 5。 拒绝访问 ” 。问题详解
Dvwa 靶场练习记录
Draw a circle quickly in MATLAB (the one that can be drawn directly given the coordinates and radius of the center of the circle)
[appium] encountered the problem of switching the H5 page embedded in the mobile phone during the test
使用 Ingress 实现金丝雀发布
How to import Excel data in SQL server, 2019 Edition
Comparison of indoor positioning methods of several intelligent robots
随机推荐
Usage of databinding
校园转转二手市场源码下载
php生成短链接:将数字转成字母,将字母转成数字
How to import Excel data in SQL server, 2019 Edition
Implementation of new
BUUCTF [ACTF2020 新生赛]Include1
Mobile web (Font Icon, plane conversion, color gradient)
How does feign integrate hystrix
Jetson Xavier NX (3) bazel mediapipe installation
Go语学习笔记 - Slice、Map | 从零开始Go语言
Summary of facial classics
渗透测试面试合集---HVV---
C 输出一种二维数组,特点如下。
一个没啥L用,但可以装X的IDEA插件
[programming practice / embedded competition] learning record of embedded competition (II): picture streaming based on TCP
[极客大挑战 2019]Havefun1
Data security has become a hidden danger. Let's see how vivo can make "user data" armor again
Principle of sentinel integrating Nacos to update data dynamically
Research on system and software security (3)
BUFFCTF文件中的秘密1