题目来源
https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/
题目搬运者
给定一个字符串s,颠倒句子中每个单词的字符顺序,同时仍然保留空格和初始语序。
只能说在做算法题中,边练习python语法的一些技巧了。
python技巧解题方法
- word[::-1] #就是对单词的一种翻转形式
- s.split(" ") #以某个字符对字符串进行切割 此处以空格进行切割
- str 类型#Python(特指Python 3)中包含字符串,字符串的类型为str,字符串是Unicode码点(Unicode code codepoint)的序列,属于不可变类型。
以下的代码主要采用python的技巧,没有思考技巧。
class Solution(object):
#Python(特指Python 3)中包含字符串,字符串的类型为str,字符串是Unicode码点(Unicode code codepoint)的序列,属于不可变类型。
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
a=""
for word in s.split(" "):
word = word[::-1]
a += word+" "
return a[0:len(a)-1] #method 1
#return a[0:-1] # method2 第二参数是负数的话,从末尾开始倒数
method 2 的用时要比method1 用时长一些些