Java: with sentinel


  • 0
    public static boolean isPalindrome(String s) {
        if (s == null || s.length() == 0) return true;
        s = s.toLowerCase();
        StringBuilder sb = new StringBuilder(s);
        sb.append('a');
        sb.insert(0, 'a');
        int i = 0, j = sb.length() - 1;
        while (i < j) {
        	while (!Character.isLetterOrDigit(sb.charAt(i))) i++;
        	while (!Character.isLetterOrDigit(sb.charAt(j))) j--;
        	if (sb.charAt(j) == sb.charAt(i)) {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.