C# Solution O(n) Time O(1) Space


  • 0
    A
        public bool ValidPalindrome(string s) {
                int length = s.Length;
                if (length <= 2) return true;
    
                int todel = 0;
                int i = 0, j = length - 1;
    
                while (i <= j)
                {
                    if (s[i] != s[j])
                    {
                        if ((s[i + 1] == s[j] && i + 1 >= j) || (s[i + 1] == s[j] && s[i + 2] == s[j - 1]))
                        {
                            todel++;
                            ++i;
                        }
                        else if ((s[i] == s[j - 1] && i >= j - 1) || (s[i] == s[j - 1] && s[i + 1] == s[j - 2]))
                        {
                            todel++;
                            --j;
                        }
                        else
                        {
                            return false;
                        }
    
                        if (todel > 1) return false;
                    }
                    else
                    {
                        ++i; --j;
                    }
                }
    
                return true;
            }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.