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.
Solution:
string removeNonAlphabetsAndConvertToUpperCase(string s)
{
for(int i=0; i<s.size(); i++)
{
if((s[i] < 'A' || s[i] > 'Z') && (s[i] < 'a' || s[i] > 'z') && (s[i] < '0' || s[i] > '9'))
{
s.erase(i,1);
i--;
}
}
transform(s.begin(), s.end(), s.begin(), ::toupper);
return s;
}
string getReverse(string s)
{
string s1;
for(int i = s.length()-1; i>=0; i--)
s1.push_back(s.at(i));
return s1;
}
bool isPalindrome(string s) {
string s2 = removeNonAlphabetsAndConvertToUpperCase(s);
string s1 = getReverse(s2);
if(s1.compare(s2) == 0)
return true;
return false;
}
Complete Code:
// function to check if it is palindrome or not
#include <bits/stdc++.h>
using namespace std;
string removeNonAlphabetsAndConvertToUpperCase(string s)
{
for(int i=0; i<s.size(); i++)
{
if((s[i] < 'A' || s[i] > 'Z') && (s[i] < 'a' || s[i] > 'z') && (s[i] < '0' || s[i] > '9'))
{
s.erase(i,1);
i--;
}
}
transform(s.begin(), s.end(), s.begin(), ::toupper);
return s;
}
string getReverse(string s)
{
string s1;
for(int i = s.length()-1; i>=0; i--)
s1.push_back(s.at(i));
return s1;
}
bool isPelendrome(string s) {
string s2 = removeNonAlphabetsAndConvertToUpperCase(s);
string s1 = getReverse(s2);
cout << s1 << endl << s2 << endl;
if(s1.compare(s2) == 0)
return true;
return false;
}
int main()
{
string s = "0p";
cout << isPelendrome(s) << endl;
return 0;
}