LintCode Q212 Space Replacement in Python

  • Jinhai ZHOU
  • 3 Minutes
  • 2016年11月13日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
# @param {char[]} string: An array of Char
# @param {int} length: The true length of the string
# @return {int} The true length of new string
def replaceBlank(self, string, length):
# Write your code here
space_count = 0
for i in xrange(length):
if string[i] == ' ':
space_count += 1
true_length = length + space_count * 2
old_index = length - 1
new_index = true_length - 1
while old_index >= 0:
if string[old_index] != ' ':
string[new_index] = string[old_index]
new_index -= 1
old_index -= 1
else:
string[new_index] = '0'
string[new_index - 1] = '2'
string[new_index - 2] = '%'
old_index -= 1
new_index -= 3
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。