|
21 | 21 |
|
22 | 22 | ## 思路
|
23 | 23 |
|
24 | | -如果想把这道题目做到极致,就不要只用额外的辅助空间了! (不过使用Java刷题的录友,一定要使用辅助空间,因为Java里的string不能修改) |
| 24 | +如果想把这道题目做到极致,就不要只用额外的辅助空间了! (不过使用Java和Python刷题的录友,一定要使用辅助空间,因为Java和Python里的string不能修改) |
25 | 25 |
|
26 | 26 | 首先扩充数组到每个数字字符替换成 "number" 之后的大小。
|
27 | 27 |
|
@@ -215,6 +215,46 @@ public class Main {
|
215 | 215 | }
|
216 | 216 | ```
|
217 | 217 |
|
| 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 | + |
218 | 258 | ### Go:
|
219 | 259 | ````go
|
220 | 260 | package main
|
|
0 commit comments