Palindrome
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
Example 1:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.
Example 3:
Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.
Constraints:
1 <= s.length <= 2 * 105
s consists only of printable ASCII characters.
1 Answer
class Check
{
public boolean checker(String word)
{
String rev = "";
String s = word.toLowerCase();
for(int i=0; i<s.length(); i++)
{
char c = s.charAt(i);
if(c >= 'a' && c <= 'z')
{
rev = rev+c;
}
if((c - '0') >= 0 && (c-'0') <=9)
{
rev = rev+c;
}
}
int i =0;
int j = rev.length()-1;
while(i<j)
{
char charAtstart = rev.charAt(i);
char charAtend = rev.charAt(j);
if(Character.compare(charAtstart,charAtend)!=0)
{
return false;
}
i++;
j--;
}
return true;
}
}
class Paldrm {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner(System.in);
System.out.println("Enter string: ");
String word = in.nextLine();
Check c = new Check();
System.out.println(c.checker(word));
in.close();
}
}