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

Reverse String

LeetCode 344 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Swap s[i] with s[n−1−i] for i < n/2.

எளிதுTwo PointersString
LeetCode இல் திற ↗

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

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

Intuition

Swap the first and last characters, then the second and second-to-last, and so on until the middle. Each swap fixes two positions.

Approach

  1. 1

    Loop i over the first half.

  2. 2

    Swap s[i] and s[n−i−1].

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

Two-ended swapPythonO(n) time · O(1) space
class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        n=len(s)
        for i in range(n//2):
            s[i],s[n-i-1]=s[n-i-1],s[i]
        return s
        
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

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

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

Swap the first and last characters, then the second and second-to-last, and so on until the middle. Each swap fixes two positions.

Reverse String (LeetCode 344) ஐ எப்படித் தீர்ப்பது?

1. Loop i over the first half. 2. Swap s[i] and s[n−i−1].

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

Time: O(n). Space: O(1). (Accepted approach: Two-ended swap.)

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

Stop at n // 2 or you'll swap everything back.