8ms Java Easy Solution


  • 0
    public class Solution {
        private boolean isAlphaNumeric(char c) {
            return (c>='a'&&c<='z') || (c>='0')&&(c<='9');
        }
        
        public boolean isPalindrome(String s) {
            if(s.length()==0 || s.length()==1)
                return true;
            
            for(int i=0,j=s.length()-1; i<j;) {
                char c1 = Character.toLowerCase(s.charAt(i));
                char c2 = Character.toLowerCase(s.charAt(j));
                boolean c1_ok = isAlphaNumeric(c1);
                boolean c2_ok = isAlphaNumeric(c2);
                if(c1_ok && c2_ok) {
                    if (c1 != c2)
                        return false;
                    i++;
                    j--;
                } else if (c1_ok) {
                    j--;
                } else if (c2_ok) {
                    i++;
                } 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.