对于刚接触的宝宝来说可能会想不明白,其实很简单,就好比赋值。
words[left],words[right]=words[right],words[left]
# 同
a, b = b, a
力扣习题. - 力扣(LeetCode)
给定一个字符串,逐个翻转字符串中的每个单词。
示例 1:
输入: "the sky is blue"
输出: "blue is sky the"
示例 2:
输入: " hello world! "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
示例 3:
输入: "a good example"
输出: "example good a"
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
# 列表法
x = input() # 键盘输入
x = x.strip() # 字符串型转列表型
x = x[::-1]
x = ' '.join(word[::-1] for word in x.split())
# 以空格为分隔符拆分字符串,再用空格拼接输出
print(x)
# 输入 I am a student
# 输出 student a am I
# 双指针
# 先将字符串拆分为单词,字符型 转换成 列表类型
s = input()
words = s.split()
# 创建双指针
left,right=0,len(words)-1
# 反转
while left<right:
words[left],words[right]=words[right],words[left]
left += 1
right -= 1
# ['student', 'a', 'am', 'I']
# 列表转换成字符串型输出
words = ' '.join(words)
print(words)
# 输入 I am a student
# 输出 student a am I