Skip to content

Commit 1d0333f

Browse files
authored
给0054.替换数字.md 加入python解法
1 parent 9f203fb commit 1d0333f

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

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

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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)