I have to check pallindrome string.I am getting a wrong answer when I enter String having numeric values.For ex."0P"

user13066649 :

I have to ignore all special characters in the string.I have created a new string s1 including only alphanumerics characters.Then,made a reverse string s2 and then checked if they are pallindrome or not.

class Solution 
{
    public boolean isPalindrome(String s)
    {
        char c,ch;
        String s1="";
        String s2="";
        s=s.trim();
        s=s.toLowerCase();
        if(s=="")
            return true;
        for(int i=0;i<s.length();i++)
        {
            c=s.charAt(i);
            if(c>=97&&c<=122||c>=0&&c<=9)
                s1=s1+c;
        }
        for(int j=s1.length()-1;j>=0;j--)
        {
            ch=s1.charAt(j);
            s2=s2+ch;
        }
    if(s1.equals(s2))
        return true;
    else
        return false;  
    }
}
Maxim Popov :

As I understand, you are using c>=0&&c<=9 for checking c for digit. It is wrong, cause '0' == 48 and '9' == 57 and you have to use c>=48 && c<=57


And I want to give you some comments about your code:

  1. String is an immutable object in java and a lot of string concatenating - is a very bad practice. Please use StringBuilder.
  2. You can use s.isEmpty() instead of s==""
  3. Character class has static methods isDigit and isAlphabetic, whic are checks char for digit or alphabetic
  4. If you will use StringBuilder, you can invert string just by stringBuilder.reverse() method
  5. At the end of the method, you return true if s1.equals(s2) and false - overwise. You can just use return s1.equals(s2);
  6. And you can iterating through the string with for (char c : s.toCharArray()) cycle

And the final code is

public static boolean isPalindrome(String s)
{
    s=s.trim();
    s=s.toLowerCase();

    if(s.isEmpty())
        return true;

    StringBuilder sanitizedString = new StringBuilder();
    for (char c : s.toCharArray()) {
        if(Character.isAlphabetic(c) || Character.isDigit(c))
            sanitizedString.append(c);
     }

    String s1 = sanitizedString.toString();
    String s2 = sanitizedString.reverse().toString();

    return s1.equals(s2)
}

And you can use regexp from @RR_IL answer for avoiding the cycle.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=417309&siteId=1