leetcode
  • Coding Interview Prep
  • Data structure
    • String
    • List
    • Matrix
    • Dictionary
    • Tuple
    • Set
    • Tree
    • Stack
  • Array
    • 1_Two Sum
    • 15_Three Sum
    • 21_Merge Two Sorted Lists
    • 26_Remove Duplicates from Sorted Array
    • 27_Remove Element
    • 31_Next Permutation
    • 56_Merge Intervals
    • 57_Insert Interval
    • 66_Plus One
    • 80_Remove Duplicates from Sorted Array II
    • 81_Search in Rotated Sorted Array II
    • 88_Merge Sorted Array
    • 121_Best Time to Buy and Sell Stock
    • 122_Best Time to Buy and Sell Stock II
    • 123_Best Time to Buy and Sell Stock III
    • 167_Two Sum II - Input array is sorted
    • 169_Majority Element
    • 170_Two Sum III - Data Structure Design
    • 189_Rotate Array
    • 238_Product of Array Except Self
    • 243_Shortest Word Distance
    • 244_Shortest Word Distance II
    • 245_Shortest Word Distance III
    • 252_Meeting Rooms
    • 277_Find the Celebrity
    • 283_Move Zeroes
    • 349_Intersection of Two Arrays
    • 350_Intersection of Two Arrays II
    • 605_Can Place Flowers
    • 653_Two Sum IV - Input is a BST
    • 674_Longest Continuous Increasing Subsequence
    • 714_Best Time to Buy and Sell Stock with Transaction Fee
    • 724_Find Pivot Index
    • 747_Largest Number At Least Twice of Others
    • Sort an Array in Wave Form
    • Permute Elements of An Array
    • Reservoir Sampling (online)
    • Reservoir Sampling (offline)
  • Matrix
    • 36_Valid Sudoku
    • 48_Rotate Image
    • 54_Spiral Matrix
    • 59_Spiral Matrix II
    • 118_Pascal's Triangle
    • 119_Pascal's Triangle II
    • 240_Search a 2D Matrix II
    • 311_Sparse Matrix Multiplication
    • 498_Diagonal Traverse
  • String
    • 5_Longest Palindromic Substring
    • 6_ZigZag Conversion
    • 14_Longest Common Prefix
    • 17_Letter Combinations of a Phone number
    • 20_Valid Parentheses
    • 28_Implement strStr()
    • 38_Count and Say
    • 43_Multiply Strings
    • 49_Group Anagrams
    • 93_Restore IP Address
    • 125_Valid Palindrome
    • 151_Reverse Words in a String
    • 157_Read N Characters Given Read4
    • 242_Valid Anagram
    • 266_Palindrome Permutation
    • 344_Reverse String
    • 387_First Unique Character in a String
    • 647_Palindromic Substrings
    • 678_Valid Parenthesis String
    • 680_Valid Palindrome II
    • 709_To Lower Case
    • 819_Most Common Word
    • 833_Find and Replace in String
  • Search
    • 33_Search in Rotated Sorted Array
    • 34_Find First and Last Position of Element in Sorted Array
    • 35_Search Insert Position
    • 153_Find Minimum in Rotated Sorted Array
    • 215_Kth Largest Element in an Array
    • 268_Missing Number
    • 278_First Bad Version
    • 339_Nested List Weight Sum
    • 364_Nested List Weight Sum II
  • Math
    • 12_Integer to Roman
    • 13_Roman to Integer
    • 29_Divide Two Integers
    • 67_Add Binary
    • 69_Sqrt(x)
    • 168_Excel Sheet Column Title
    • 171_Excel Sheet Column Number
    • 204_Count Primes
    • 504_Base 7
    • 628_Maximum Product of Three Numbers
    • Multiply Two Integers
    • Smallest Non-constructible Value
    • SORT5
  • DP
    • 53_Maximum Subarray
    • 152_Maximum Product Subarray
    • 256_Paint House
    • 300_ Longest Increasing Subsequence
    • 747_Min Cost Climbing Stairs
    • 377_Combination Sum IV
  • Hash Table
    • 535_Encode and Decode TinyURL
  • Tree
    • 94_Binary Tree Inorder Traversal
    • 102_Binary Tree Level Order Traversal
    • 103_Binary Tree Zigzag Level Order Traversal
    • 104_Maximum Depth of Binary Tree
    • 113_Path Sum II
    • 144_Binary Tree Preorder Traversal
    • 145_Binary Tree Postorder Traversal
    • 235_Lowest Common Ancestor of a Binary Search Tree
    • 236_Lowest Common Ancestor of a Binary Tree
    • 257_Binary Tree Paths
    • 404_Sum of Left Leaves
    • 543_Diameter of Binary Tree
    • 572_Subtree of Another Tree
    • 637_Average of Levels in Binary Tree
  • Linked List
    • 2_Add Two Numbers
    • 206_Reverse Linked List
    • 234_Palindrome Linked List
  • Recursion
    • Tower of Hanoi
  • Backtracking
    • 51_N-Queens
    • 52_N-Queens II
    • 46_ Permutations
    • 77_ Combinations
    • 78_Subsets
    • 22_Generate Parentheses
    • 131_ Palindrome Partitioning
  • Bit Manipulation
    • 461_Hamming Distance
  • Python
    • for ... else ...
    • dictionary.get( ) vs dictionary[ ]
    • Read and write data file
    • List Comprehension
    • Lambda
    • Receiving Tuples and Dictionaries as Function Parameters
    • The assert statement
    • Miscellaneous
    • Python shortcuts
  • template
  • facebook
Powered by GitBook
On this page
  • Test case 1 (easy)
  • Test case 2 (with spaces at the beginning and the end)
  • Test case 3 (only spaces in the string)
  • Test case 4 (empty string)
  • Test case 5 (more than one space between words)
  • Idea 1
  • Complexity 1
  • Solution 1_v1 (with build-in functions split(), reverse(), join())
  • Solution 1_v2 (write split(), use build in reverse(), join())
  • Idea 2
  • Complexity 2
  • Solution 2
  • Idea 3
  • Complexity 3

Was this helpful?

  1. String

151_Reverse Words in a String

[medium]

Given an input string, reverse the string word by word.

Note: need to make sure that the string only contains letters and spaces.

Test case 1 (easy)

Input: "the weather is good"
Output: "good is weather the"

Test case 2 (with spaces at the beginning and the end)

Input: "   the weather is good   "
Output: "good is weather the"

Test case 3 (only spaces in the string)

Input: "      "
Output: ""

Test case 4 (empty string)

Input: ""
Output: ""

Test case 5 (more than one space between words)

Input: "the    weather    is     good"
Output: "good is weather the"

Idea 1

  • extract all words in to a list

  • reverse the list

  • join strings in the list with space

Complexity 1

  • Time: O(n)O(n)O(n)

  • Space: O(n)O(n)O(n)

Solution 1_v1 (with build-in functions split(), reverse(), join())

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """

        out = " ".join(reversed(s.split()))
        return out

Solution 1_v2 (write split(), use build in reverse(), join())

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """

        out = []        
        word = ""

        # split the string into a list of words
        for i in range(len(s)) :
            # if current character is not space, add it to word
            # if current character is space,and word is not empty, 
            # append current word to out and set word to empty
            # otherwise, continue with next character
            if s[i] != " " :
                word += s[i]
            elif word != "" :
                out.append(word)
                word = ""
            else :
                continue

        # if sting is not empty and last character is not space,
        # add current word to out
        if len(s) > 0 and s[-1] != " " :
            out.append(word)

        # reverse the list, then join with space
        return " ".join(reversed(out))

Idea 2

  • reverse the entire string

  • loop over the string, reverse the words, append space after each word, and neglect all the spaces.

Complexity 2

  • Time: O(n)O(n)O(n)

  • Space: O(n)O(n)O(n)

Solution 2

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """

        # current word
        word = ""
        # output reversed string
        out = ""

        # reverse input string
        s = s[ : :-1]

        for i in range(len(s)) :
            # For first letter in words except the first word, 
            # put the current stored word into out, let current word be the current letter.
            if s[i] != " " and s[i-1] == " " and word != "":
                out += word + " "
                word = s[i] 
            # For all other letters, update current word in a reversed order.
            elif s[i] != " " :
                word = s[i] + word
            # Skip all the spaces.
            else :
                continue
        # store the last word
        out += word
        return out

Idea 3

  • reverse the entire string

  • loop over the string, reverse the words, append space after each word, and neglect all the spaces.

  • do everything in-place

Complexity 3

  • Time: O(n)O(n)O(n)

  • Space: O(1)O(1)O(1)

def reverseWords(s):
    """
    :type s: str
    :rtype: str
    """
    if s == "": return s
    s = list(s)

    # reverse the input string first
    s.reverse()

    # reverse each word
    start, end = 0, 0
    while end < len(s):
        if not s[end] == " ":
            end += 1
        elif start < end:
            # just finish one word
            s[start:end] = reversed(s[start:end])
            end += 1
            start = end
        elif start == end:  
            # the string starts with space or
            # there are multiple spaces between words
            s.pop(end)
    if start < end:
        # the last word is not reversed yet
        s[start:end] = reversed(s[start:end])
    if len(s) >= 1 and s[-1] == " ":
        # the string ends with space
        s.pop()
    return "".join(s)
Previous125_Valid PalindromeNext157_Read N Characters Given Read4

Last updated 5 years ago

Was this helpful?