C++/Java/Python, concise code


  • 0
    Z

    C++

    class Solution {
    public:
        bool validPalindrome(string s) {
            int n = s.size(), i = 0, j = n-1;
            while (i < j && s[i] == s[j]) i++, j--;
            return isvalid(s, i+1, j) || isvalid(s, i, j-1);
        }
    private:
        bool isvalid(string& s, int l, int r) {
            while (l < r && s[l] == s[r]) l++, r--;
            return l >= r;
        }
    };
    

    Python

    class Solution(object):
        def helper(self, s, l, r):
            while l < r and s[l] == s[r]:
                l += 1
                r -= 1
            return l >= r
        def validPalindrome(self, s):
            i, j = 0, len(s)-1
            while i < j and s[i] == s[j]:
                i += 1
                j -= 1
            return self.helper(s, i, j-1) or self.helper(s, i+1, j)
    

    Java

    class Solution {
        public boolean validPalindrome(String s) {
            int n = s.length(), i = 0, j = n-1;
            while (i < j && s.charAt(i) == s.charAt(j)) {
                i++;
                j--;
            }
            return isPalindrome(s, i, j-1) || isPalindrome(s, i+1, j);
        }
        private boolean isPalindrome(String s, int l, int r) {
            while (l < r && s.charAt(l) == s.charAt(r)) {
                l++;
                r--;
            }
            return l >= r;
        }
    }
    

Log in to reply
 

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