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.