题目:请实现一个函数,把字符串中的每个空格替换成"%20"。例如输入"We are happy.",则输出"We%20are%20happy."。
class Solution {
func replace(_ s: String) -> String {
guard s.count > 0 else {
return s
}
var nullNum = 0
for c in s {
if c == " " {
nullNum += 1
}
}
let len = s.count + nullNum * 2
var list = Array<Character>(repeating: "x", count: len)
var listIndex = len - 1
for (_,c) in s.enumerated().reversed() {
if c == " " {
list[listIndex] = "0"
listIndex -= 1
list[listIndex] = "2"
listIndex -= 1
list[listIndex] = "%"
listIndex -= 1
}else {
list[listIndex] = c
listIndex -= 1
}
}
return String(list)
}
}
解题思路:如果从前往后处理,则空格后面所有的字符都后移若干位。所以从后向前处理会有更优解。这里直接新建了一个数组模拟操作的。
github地址:https://github.com/cubegao/LeetCode