题解 | #二维数组中的查找#
替换空格
http://www.nowcoder.com/practice/0e26e5551f2b489b9f58bc83aa4b6c68
编程打卡第一天:
解法1:继续list.append
class Solution:
def replaceSpace(self , s: str) -> str:
# write code here
result = []
for strs in s:
if strs == ' ':
strs = "%20"
result.append(strs)
return ''.join(result)
不足之处在于输出是list而非str,所以最后return还要进行join操作,针对字符串可以有以下改写:
解法2:
class Solution:
def replaceSpace(self , s: str) -> str:
res = ""
#遍历字符串
for i in s:
#非空格直接复制
if i != ' ':
res += i
#空格就替换
else:
res += "%20"
return res
key point:
- 空字符串的定义为:""
2.类似于list的append,对于字符串可以直接用+=