题目链接🔗:路径加密
假定一段路径记作字符串
path
,其中以 ".
" 作为分隔符。现需将路径加密,加密方法为将path
中的分隔符替换为空格 "",请返回加密后的字符串。
示例 1:
输入:path = "a.aef.qerf.bb" 输出:"a aef qerf bb”
思路:按照 "."进行切分后用空格连接
解法1:
class Solution(object):
def pathEncryption(self, path):
"""
:type path: str
:rtype: str
"""
return " ".join(path.split("."))
解法2:
lass Solution(object):
def pathEncryption(self, path):
"""
:type path: str
:rtype: str
"""
res = []
for i in path:
if i != ".":
res.append(i)
else:
res.append(" ")
return ''.join(res)
题目链接🔗:反转字符串里面的单词
给定一个字符串,逐个翻转字符串中的每个单词。
示例 1:
输入: "the sky is blue"
输出: "blue is sky the"示例 2:
输入: " hello world! "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。示例 3:
输入: "a good example"
输出: "example good a"
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
正确代码:
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
words = s.split()
left,right = 0,len(words) -1
while right>left:
words[left],words[right] = words[right],words[left]
left+=1
right -=1
return ' '.join(words)