↓Skip to main content
  1. LeetCode/

LeetCode 557: Reverse Words in a String III

·1 min· ·
LeetCode Easy Two-Pointers String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-27

  • Submissions: Accepted ×2

Approach
#

Words are separated by single spaces with none at the ends, so split(" "), reverse each word, and join with spaces (Two Pointers Template 1’s reversal, via slicing in Python).

My Solution
#

class Solution:
    def reverseWords(self, s: str) -> str:
        return " ".join(w[::-1] for w in s.split(" "))

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Reverse each word, not the order of words.

Interview Explanation
#

I split into words, reverse each, and join them with spaces. Time O(n).

Related

LeetCode 345: Reverse Vowels of a String
·1 min
LeetCode Easy Two-Pointers String
LeetCode 345 note: the same two pointers as LC 917, with the condition switched to “is a vowel” (both cases)
LeetCode 541: Reverse String II
·1 min
LeetCode Easy Two-Pointers String
LeetCode 541 note: in every block of 2k reverse the first k; when fewer than k remain reverse them all, which slicing handles automatically
LeetCode 344: Reverse String
·1 min
LeetCode Easy Two-Pointers String
LeetCode 344 note: swap with two pointers and move inward to reverse in place
LeetCode 392: Is Subsequence
·2 mins
LeetCode Easy Two-Pointers String Dynamic-Programming
LeetCode 392 note: two pointers; the pointer on t always advances, and the one on s advances on a match; bound-check both
LeetCode 125: Valid Palindrome
·2 mins
LeetCode Easy Two-Pointers String
LeetCode 125 note: two pointers skip non-alphanumeric characters and compare lowercase letters, with digits included
LeetCode 28: Find the Index of the First Occurrence in a String
·1 min
LeetCode Easy Two-Pointers String String-Matching Z-Algorithm
LeetCode 28 note: try matching needle at every start, or use str.find; index raises when not found