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.