题解 | #翻转单词序列#
翻转单词序列
https://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3
这道题的思路是先把字符串整体反转,然后根据单词间的空格对单词进行 二次翻转。
主要实现 流程 如下:
input:str,output:str 1.s=[i for i in str]#遍历字符串生成包含空格的列表。(之所以 遍历,用 split()会跳过空格) 2.s.reverse()#初步反转列表 3.zero_index=[0]+[i for i in range(len(s)) if s[i]==" " ]+[len(s)]#找到列表 中有空格 符 ‘’的索引,这里加上头尾是为了后续的遍历 4.for i in range(len(zero_index)-1):#按照空格索引,把空格间的字符翻转,并更新 s z = s[zero_index[i]:zero_index[i + 1]] z.reverse() if ' ' in z:#解决‘’空格符前后问题 z.remove(' ') z.insert(0,' ') s[zero_index[i]:zero_index[i + 1]]=z 5.s=''.join(s)#把翻转后的列表拼接成字符串,后续在核心代码模式下return出去即可。
