LeetCode Brush Questions Interview Question 58-I. Reverse the order of words

LeetCode Brush Questions Interview Question 58-I. Reverse the order of words

I don't know where I am going, but I am already on my way!
Time is hurried, although I have never met, but I met Yusi, it is really a great fate, thank you for your visit!
  • Topic :
    Enter an English sentence and reverse the order of the words in the sentence, but the order of the characters in the word remains unchanged. For simplicity, punctuation marks are treated like ordinary letters. For example, input the string "I am a student.", then output "student. a am I".
  • Example :
示例 1 :
输入: "the sky is blue"
输出: "blue is sky the"
示例 2 :
输入: "  hello world!  "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
示例 3 :
输入: "a good   example"
输出: "example good a"
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
  • Description :
    • No space characters form a word.
    • The input string can contain extra spaces before or after it, but the reversed characters cannot be included.
    • If there is an extra space between two words, reduce the space between the words after inversion to only one.
  • Code:
class Solution:
    def reverseWords(self, s: str) -> str:
        s = s +  ' '
        result = ""
        temp = []
        for i in range(0,len(s)):
            if s[i] != ' ':
                temp.append(s[i])
                continue
            elif s[i] == ' ' and s[i-1] != ' ':
                result = ' ' + ''.join(temp) + result
                temp = []
                continue
            elif s[i] == ' ' and s[i-1] == ' ': continue 
        return result[1:]
# 执行用时 :56 ms, 在所有 Python3 提交中击败了20.70%的用户
# 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了100.00%的用户
  • Algorithm description:
    create an empty stack tempand push sthe elements in the stack one by one; if the current element is not a space, push the element into the stack; if the current element is a space, and the previous element is not a space, it means that a word traversal is complete, and the elements in the stack are The output is in the form of a string, appended to the resultprevious one result = ' ' + ''.join(temp) + result, and the stack is tempcleared; if the current element and the previous element are both spaces, continue to traverse the next element. Considering that there may be no space after the last word, it will be omitted, so sadd a space after it s = s + ' '; when adding words to the result, each word has a space before it, so when returning the result, remove the first space result[1:].

Guess you like

Origin blog.csdn.net/qq_34331113/article/details/106605052