Shall we ignore non-alphanumeric characters?


  • 2
    N

    Input: "1a2"

    Output: true

    Expected: false

    Here is my code: I thought we need to ignore non-alphanumeric characters

    public boolean isPalindrome(String s) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(s.isEmpty()) return true;
        s=s.replaceAll("[^a-zA-Z]", "");
        s=s.toLowerCase();
        int length=s.length();
        int i=0;
        int j=length-1;
        boolean validPadindrome=true;
        while(i<=j) {
            if(!(s.charAt(i)>='a'&&s.charAt(i)<='z')) i++;
            if(!(s.charAt(j)>='a'&&s.charAt(j)<='z')) j--;
            if(s.charAt(i)==s.charAt(j)) {
                i++;
                j--;
            } else {
                validPadindrome=false;
                break;
            }
        }
        return validPadindrome;
    }

  • 1
    A

    this line should be:

    s=s.replaceAll("[^a-zA-Z0-9]", "");

    remove these two lines:

    if(!(s.charAt(i)>='a'&&s.charAt(i)<='z')) i++;
    if(!(s.charAt(j)>='a'&&s.charAt(j)<='z')) j--;


  • 0
    N

    didn't pay attention it's "alphanumeric" characters


Log in to reply
 

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