Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 151 · Two Pointers

Reverse Words in a String

LeetCode 151 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Trim → reverse everything → reverse each word.

நடுத்தரம்Two PointersString
LeetCode இல் திற ↗

நான் Reverse Words in a String (LeetCode 151) ஐ இப்படித் தீர்த்தேன் — Two Pointers பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

Do it the in-place way: clean up the spaces, reverse the whole character list so the words are in the right order, then reverse each word individually so its letters read forwards again.

Approach

  1. 1

    Copy characters skipping leading/trailing spaces and collapsing runs of spaces.

  2. 2

    Reverse the full list.

  3. 3

    Walk word by word, reversing each one back.

  4. 4

    Join into a string.

நான் எப்படித் தீர்த்தேன்

Reverse all, then each wordPythonO(n) time · O(n) space
class Solution:
    def reverseWords(self, s: str) -> str:
        def remove_space(l):
            left=0
            right=len(l)-1
            output = []
            while left<=right and s[left]==" ":
                left+=1
            while left<=right and s[right]==" ":
                right-=1
            while left<=right:
                if s[left]!=" ":
                    output.append(s[left])
                elif output[-1]!=" ":
                    output.append(s[left])
                left+=1
            return output
        def reverse(l,start,end):
            while start<end:
                l[start],l[end]=l[end],l[start]
                start+=1
                end-=1
        def reverse_word(l):
            n=len(l)
            start=0
            end=0
            while start<len(l):
                while end<n and l[end]!=" ":
                    end+=1
                reverse(l,start,end-1)
                start=end+1
                end+=1
        l=remove_space(s)
        reverse(l,0,len(l)-1)
        reverse_word(l)
        return "".join(l)

ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Reverse Words in a String — அடிக்கடி கேட்கப்படும் கேள்விகள்

Reverse Words in a String பின்னாலுள்ள intuition என்ன?

Do it the in-place way: clean up the spaces, reverse the whole character list so the words are in the right order, then reverse each word individually so its letters read forwards again.

Reverse Words in a String (LeetCode 151) ஐ எப்படித் தீர்ப்பது?

1. Copy characters skipping leading/trailing spaces and collapsing runs of spaces. 2. Reverse the full list. 3. Walk word by word, reversing each one back. 4. Join into a string.

Reverse Words in a String இன் time மற்றும் space complexity என்ன?

Time: O(n). Space: O(n) for the character list. (Accepted approach: Reverse all, then each word.)

Reverse Words in a String இல் பொதுவான தவறுகள் என்ன?

Collapse repeated spaces between words to a single one.