Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 680 · Two Pointers

Valid Palindrome II

LeetCode 680 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

On the first mismatch, try both deletions once.

సులభంTwo PointersStringGreedy
LeetCode లో తెరవండి ↗

నేను Valid Palindrome II (LeetCode 680) ను ఇలా పరిష్కరించాను — Two Pointers ప్యాటర్న్‌లోని ఒక సులభం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.

కింది వివరణ ఇంగ్లీష్‌లో ఉంది.

Intuition

Walk inward from both ends. At the first mismatch you get one deletion: try skipping the left character or the right character, and check whether what remains between the pointers is a palindrome.

Approach

  1. 1

    Two pointers from the ends.

  2. 2

    Matching characters: move inward.

  3. 3

    Mismatch: return palindrome(i+1, j) or palindrome(i, j−1).

నేను ఎలా పరిష్కరించాను

Two pointers + one skipPythonO(n) time · O(1) space
class Solution:
    def check_palindrome(self,i,j,s) ->bool:
        while i<j:
            if s[i]!=s[j]:
                return False
            i+=1
            j-=1        
        return True

    def validPalindrome(self, s: str) -> bool:
        i,j=0,len(s)-1
        while(i<j):
            #Found a mismatched pair, try both deletions
            if s[i]!=s[j]:
                return self.check_palindrome(i+1,j,s) or self.check_palindrome(i,j-1,s)
            i=i+1
            j=j-1
        return True
స్టెప్-త్రూ లోడ్ అవుతోంది…

Valid Palindrome II — తరచూ అడిగే ప్రశ్నలు

Valid Palindrome II వెనుక ఉన్న intuition ఏమిటి?

Walk inward from both ends. At the first mismatch you get one deletion: try skipping the left character or the right character, and check whether what remains between the pointers is a palindrome.

Valid Palindrome II (LeetCode 680) ను ఎలా పరిష్కరించాలి?

1. Two pointers from the ends. 2. Matching characters: move inward. 3. Mismatch: return palindrome(i+1, j) or palindrome(i, j−1).

Valid Palindrome II యొక్క time, space complexity ఎంత?

Time: O(n). Space: O(1). (Accepted approach: Two pointers + one skip.)

Valid Palindrome II లో సాధారణ పొరపాట్లు ఏమిటి?

Only one deletion is allowed — don't recurse with another deletion budget.