mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-12 05:20:59 +08:00
@ -21,7 +21,7 @@
|
|||||||
|
|
||||||
## 思路
|
## 思路
|
||||||
|
|
||||||
如果想把这道题目做到极致,就不要只用额外的辅助空间了! (不过使用Java刷题的录友,一定要使用辅助空间,因为Java里的string不能修改)
|
如果想把这道题目做到极致,就不要只用额外的辅助空间了! (不过使用Java和Python刷题的录友,一定要使用辅助空间,因为Java和Python里的string不能修改)
|
||||||
|
|
||||||
首先扩充数组到每个数字字符替换成 "number" 之后的大小。
|
首先扩充数组到每个数字字符替换成 "number" 之后的大小。
|
||||||
|
|
||||||
@ -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:
|
||||||
````go
|
````go
|
||||||
package main
|
package main
|
||||||
|
Reference in New Issue
Block a user