題目:請實(shí)現(xiàn)一個(gè)函數(shù)蚪战,把字符串中的每個(gè)空格替換成"%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)
}
}
解題思路:如果從前往后處理瞎疼,則空格后面所有的字母都后移若干位。所以從后向前處理會有更優(yōu)解壁畸。這里直接新建了一個(gè)數(shù)組模擬操作的贼急。
非特殊說明,本博所有文章均為博主原創(chuàng)捏萍。
如若轉(zhuǎn)載太抓,請注明出處:https://cubegao.com/archives/replace_spaces.html