Topic
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/ti-huan-kong-ge-lcof
Solution one: the use Python replace () function. replace () Syntax: str.replace (old, new [, max]), replace the old string new, alternatively no more than the number of times max
class Solution:
def replaceSpace(self, s: str) -> str:
return s.replace(" ","%20")
Solution two: s to convert a string list, the list will replace spaces "20%", using the join () splice string, the string is returned after splicing, str.join (sequence), sequence is to be connected character sequences, splicing in accordance with the specified format
class Solution:
def replaceSpace(self, s: str) -> str:
arr = [str(x) for x in s]
for i in range(len(arr)):
if arr[i]==" ":
arr[i] = "%20"
return ''.join(arr)
Solution three: Converts a string into a list of s, the spaces in the replacement list, "20%" and "+" sign string concatenation string returned splicing
class Solution:
def replaceSpace(self, s: str) -> str:
arr = [str(x) for x in s]
for i in range(len(arr)):
if arr[i] == " ":
arr[i] = "%20"
str1 = ""
for i in arr:
str1 += i
return str1