Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5bd753f

Browse files
Merge pull request #2873 from iqna126/master
添加0054.替换数字.md python版本
2 parents d1419b1 + 163c3f3 commit 5bd753f

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

‎problems/kamacoder/0054.替换数字.md‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121

2222
## 思路
2323

24-
如果想把这道题目做到极致,就不要只用额外的辅助空间了! (不过使用Java刷题的录友,一定要使用辅助空间,因为Java里的string不能修改)
24+
如果想把这道题目做到极致,就不要只用额外的辅助空间了! (不过使用Java和Python刷题的录友,一定要使用辅助空间,因为Java和Python里的string不能修改)
2525

2626
首先扩充数组到每个数字字符替换成 "number" 之后的大小。
2727

@@ -215,6 +215,46 @@ public class Main {
215215
}
216216
```
217217

218+
### Python:
219+
```python
220+
class Solution(object):
221+
def subsitute_numbers(self, s):
222+
"""
223+
:type s: str
224+
:rtype: str
225+
"""
226+
227+
count = sum(1 for char in s if char.isdigit()) # 统计数字的个数
228+
expand_len = len(s) + (count * 5) # 计算扩充后字符串的大小, x->number, 每有一个数字就要增加五个长度
229+
res = [''] * expand_len
230+
231+
new_index = expand_len - 1 # 指向扩充后字符串末尾
232+
old_index = len(s) - 1 # 指向原字符串末尾
233+
234+
while old_index >= 0: # 从后往前, 遇到数字替换成"number"
235+
if s[old_index].isdigit():
236+
res[new_index-5:new_index+1] = "number"
237+
new_index -= 6
238+
else:
239+
res[new_index] = s[old_index]
240+
new_index -= 1
241+
old_index -= 1
242+
243+
return "".join(res)
244+
245+
if __name__ == "__main__":
246+
solution = Solution()
247+
248+
while True:
249+
try:
250+
s = input()
251+
result = solution.subsitute_numbers(s)
252+
print(result)
253+
except EOFError:
254+
break
255+
256+
```
257+
218258
### Go:
219259
````go
220260
package main

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /