Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Reverse Words in a String II

Posted on February 11, 2018July 26, 2020 by braindenny

Reverse Words in a String II



Similar Problems:

  • Series: Reverse List/String & Follow-up
  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #reverseitem, #string

Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.

The input string does not contain leading or trailing spaces and the words are always separated by a single space.

For example,

Given s = "the sky is blue",
return "blue is sky the".

Could you do it in-place without allocating extra space?

Update (2017-10-16):
We have updated the function signature to accept a character array, so please reset to the default code definition by clicking on the reload button above the code editor. Also, Run Code is now available!

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


## https://code.dennyzhang.com/reverse-words-in-a-string-ii
## Basic Ideas: two pointer
##
##  Double reverse
##
## Complexity: Time O(n), Space O(1)
class Solution:
    def reverseWords(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        def reverse(left, right):
            while left<right:
                s[left], s[right] = s[right], s[left]
                left, right = left+1, right-1

        reverse(0, len(s)-1)
        prev = 0
        for i in range(len(s)+1):
            if i == len(s) or s[i] == " ":
                reverse(prev, i-1)
                prev = i+1
linkedin
github
slack

Post Views: 3
Posted in MediumTagged #reverseitem, #string

Post navigation

Lintcode: Movie Network
LeetCode: Two Sum III – Data structure design

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.