当前位置:网站首页>LeetCode簡單題之計算字符串的數字和
LeetCode簡單題之計算字符串的數字和
2022-04-23 08:14: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://yzsam.com/2022/04/202204230701590490.html
边栏推荐
- PHP generates short links: convert numbers to letters and letters to numbers
- vivo,硬件安全的爱与雷霆
- Weekly leetcode - 06 array topics 7 ~ 739 ~ 50 ~ offer 62 ~ 26 ~ 189 ~ 9
- Smart business card applet business card details page function implementation key code
- [go] common concurrency model [generic version]
- Brief description of CPU
- Data security has become a hidden danger. Let's see how vivo can make "user data" armor again
- Cloud computing skills competition -- the first part of openstack private cloud environment
- 雲計算技能大賽 -- openstack私有雲環境 第一部分
- Move layout (Flex layout, viewport label)
猜你喜欢
随机推荐
Flatten arrays
Talking about distributed storage from ES, mongodb, redis and rocketmq
为什么会存在1px问题?怎么解决?
有意思的js 代码
谈谈那些基础但不简单的股票数据
以下程序实现从字符串str中删除第i个字符开始的连续n个字
Manipulator motion planning in 3C assembly
使用 Ingress 实现金丝雀发布
Compiling principle questions - with answers
User manual of Chinese version of solidity ide Remix
CSV column extract column extraction
Usage of databinding
【无标题】
Jetson Xavier NX(3)Bazel Mediapipe 安装
[programming practice / embedded competition] learning record of embedded competition (II): picture streaming based on TCP
Ubuntu安装Mysql并查询平均成绩
WordPress爱导航主题 1.1.3 简约大气网站导航源码网址导航源码
[untitled]
GUI,CLI与Unix哲学
Quick rehearsal exercise
![[极客大挑战 2019]Havefun1](/img/8b/b15bf31771d54db25f24d630e64093.png)








