剑指 Offer 58 - I. 翻转单词顺序

剑指 Offer 58 - I. 翻转单词顺序

输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. “,则输出"student. a am I”。

示例 1:


输入: "the sky is blue"

输出: "blue is sky the"

示例 2:


输入: "  hello world!  "

输出: "world! hello"

解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。

示例 3:


输入: "a good   example"

输出: "example good a"

解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

说明:

无空格字符构成一个单词。

输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。

如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

来源:力扣(LeetCode)

链接:力扣

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

一解

使用双指针,从字符串尾开始遍历,利用双指针确定一个单词:

使 l 指向下一个空格处, r 指向上一个单词的末尾,即可确定单词 “is” (s[l+1, r+1]


class Solution:

    def reverseWords(self, s: str) -> str:

        s = s.strip()

        res = []

        l = r = len(s) - 1

        while l >= 0:

            while l >= 0 and s[l] != " ": l -=1 # 确定单词

            res.append(s[l+1 :r + 1])

            while s[l] == " ": l -= 1 # l 指向下一个单词的末尾

            r = l 

        return " ".join(res)

        

def fff(ss):
    l = list(ss.split(' '))
    y = [i for i in l if i != '']
    y.reverse()
    m = ' '.join(y)
    return m


assert fff('the sky is blue') == 'blue is sky the'
assert fff('I am a student.') == 'student. a am I'
assert fff(' a good   example  ') == 'example good a'
def reverseWords(s: str) -> str:
    # 去除首尾多余空格
    s = s.strip()
    # 将字符串用空格分割成列表
    list_s = s.split(" ")
    # 将列表元素反转
    list_s = list_s[::-1]
    # 去除列表内的空值元素
    list_s = [ x for x in list_s if x != '' ]
    # 将列表内元素用空格连接转化为字符串
    result = " ".join(list_s)
    # 返回字符串结果
    return result


assert reverseWords("the sky is blue") == "blue is sky the"
assert reverseWords("  hello world!  ") == "world! hello"
assert reverseWords("a good   example") == "example good a"
def reversWord(args):
    # 去除首尾空格
    args = args.strip(" ")
    # 将字符串分割成列表
    L = args.split(" ")
    L1 = []
    index = len(L)
    for i in range(index):
        index -= 1
    # 将列表中非空元素,倒序插入新列表
        if L[index]:
            L1.append(L[index])
    # 合并
    new_world = ' '.join(L1)
    return new_world


assert reversWord("the sky is blue") == "blue is sky the"
assert reversWord("  hello world!  ") == "world! hello"
assert reversWord("a good   example") == "example good a"

很棒,日常肯定这么写,但是算法一般不让使用 join 或者 reverse 这种原生方法