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.