Java solutions with and without regex


  • 1
    J
        public boolean isPalindrome(String s) {
            s = s.replaceAll("\\W","");
            s = s.toLowerCase();
            if(s==null)   return false;
            for(int i=0,j=s.length()-1;i<j;i++,j--){
                if(s.charAt(i)!=s.charAt(j))    return false;
            }
            return true;
        }
    
        //without regex
        public boolean isPalindrome(String s) {
            s = s.toLowerCase();
            if(s==null)   return false;
            for(int i=0,j=s.length()-1;i<j;i++,j--){
                while(i<s.length()&&!(Character.isAlphabetic(s.charAt(i))||Character.isDigit(s.charAt(i)))) i++;
                while(j>=0&&!(Character.isAlphabetic(s.charAt(j))||Character.isDigit(s.charAt(j)))) j--;
                if(i<j&&s.charAt(i)!=s.charAt(j))    return false;
            }
            return true;
        }
    

    Two Solutions. Hope enjoy!


Log in to reply
 

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