Java solution, isPalindrome


  • 9

    Follow normal way (two pointers) to check if s is palindrome. When two chars are not equal, try to skip (pseudo delete) either left one or right one and continue checking.

    class Solution {
        public boolean validPalindrome(String s) {
            int i = 0, j = s.length() - 1;
            while (i < j && s.charAt(i) == s.charAt(j)) {
                i++; j--;
            }
    
            if (i >= j) return true;
    
            if (isPalin(s, i + 1, j) || isPalin(s, i, j - 1)) return true;
            return false;
        }
    
        private boolean isPalin(String s, int i, int j) {
            while (i < j) {
                if (s.charAt(i) == s.charAt(j)) {
                    i++; j--;
                }
                else return false;
            }
            return true;
        }
    }
    

Log in to reply
 

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