From 1d0333f59634bc68b9c4f253f95a2ef8f7a5009e Mon Sep 17 00:00:00 2001 From: Anqi Li <103280095+iqna126@users.noreply.github.com> Date: Wed, 15 Jan 2025 17:16:40 -0800 Subject: [PATCH 1/2] =?UTF-8?q?=E7=BB=990054.=E6=9B=BF=E6=8D=A2=E6=95=B0?= =?UTF-8?q?=E5=AD=97.md=20=E5=8A=A0=E5=85=A5python=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/kamacoder/0054.替换数字.md | 40 +++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/problems/kamacoder/0054.替换数字.md b/problems/kamacoder/0054.替换数字.md index de0ab1a3..e4b5c43f 100644 --- a/problems/kamacoder/0054.替换数字.md +++ b/problems/kamacoder/0054.替换数字.md @@ -215,6 +215,46 @@ public class Main { } ``` +### Python: +```python +class Solution(object): + def subsitute_numbers(self, s): + """ + :type s: str + :rtype: str + """ + + count = sum(1 for char in s if char.isdigit()) # 统计数字的个数 + expand_len = len(s) + (count * 5) # 计算扩充后字符串的大小, x->number, 每有一个数字就要增加五个长度 + res = [''] * expand_len + + new_index = expand_len - 1 # 指向扩充后字符串末尾 + old_index = len(s) - 1 # 指向原字符串末尾 + + while old_index >= 0: # 从后往前, 遇到数字替换成“number” + if s[old_index].isdigit(): + res[new_index-5:new_index+1] = "number" + new_index -= 6 + else: + res[new_index] = s[old_index] + new_index -= 1 + old_index -= 1 + + return "".join(res) + +if __name__ == "__main__": + solution = Solution() + + while True: + try: + s = input() + result = solution.subsitute_numbers(s) + print(result) + except EOFError: + break + +``` + ### Go: ````go package main From 163c3f33d8d24735230b25ddb697d726f0d5c242 Mon Sep 17 00:00:00 2001 From: Anqi Li <103280095+iqna126@users.noreply.github.com> Date: Thu, 23 Jan 2025 08:16:44 -0800 Subject: [PATCH 2/2] =?UTF-8?q?0054.=E6=9B=BF=E6=8D=A2=E6=95=B0=E5=AD=97.m?= =?UTF-8?q?d=20=E5=9C=A8=E8=AE=B2=E8=A7=A3=E4=B8=AD=E5=8A=A0=E5=85=A5?= =?UTF-8?q?=E4=BA=86python=20string=E4=B9=9F=E4=B8=8D=E5=8F=AF=E5=8F=98?= =?UTF-8?q?=E7=9A=84=E8=A7=A3=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/kamacoder/0054.替换数字.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/kamacoder/0054.替换数字.md b/problems/kamacoder/0054.替换数字.md index e4b5c43f..f788d65b 100644 --- a/problems/kamacoder/0054.替换数字.md +++ b/problems/kamacoder/0054.替换数字.md @@ -21,7 +21,7 @@ ## 思路 -如果想把这道题目做到极致,就不要只用额外的辅助空间了! (不过使用Java刷题的录友,一定要使用辅助空间,因为Java里的string不能修改) +如果想把这道题目做到极致,就不要只用额外的辅助空间了! (不过使用Java和Python刷题的录友,一定要使用辅助空间,因为Java和Python里的string不能修改) 首先扩充数组到每个数字字符替换成 "number" 之后的大小。