palindrome string code example
Example 1: Write a function that tests whether a string is a palindrome
def palindrome_check(string):
string = list(string)
tmp = []
for x in range(0, len(string)):
if(string[x] != " "):
tmp.append(string[x].lower())
array1 = []
i = 0
j = len(tmp)-1
while(i < len(tmp)):
array1.append(tmp[j])
i += 1
j -= 1
counter = 0
for x in range(0, len(tmp)):
if(tmp[x] == array1[x]):
counter += 1
if(counter == len(tmp)):
return True
return False
Example 2: check if palindrome
function isPalindrome(str) {
str = str.toLowerCase();
return str === str.split("").reverse().join("");
}
Example 3: reads the string in then determines if the string is a palindrome.
using namespace std;
// Iterative function to check if given string is a palindrome or not
bool isPalindrome(string str)
{
int low = 0;
int high = str.length() - 1;
while (low < high)
{
// if mismatch happens
if (str[low] != str[high])
return false;
low++;
high--;
}
return true;
}
int main()
{
string str = "XYXYX";
if (isPalindrome(str))
cout << "Palindrome";
else
cout << "Not Palindrome";
return 0;
}
Example 4: find all the palindrome substring in a given string
using namespace std;
// expand in both directions of low and high to find all palindromes
void expand(string str, int low, int high, auto &set)
{
// run till str[low.high] is a palindrome
while (low >= 0 && high < str.length()
&& str[low] == str[high])
{
// push all palindromes into the set
set.insert(str.substr(low, high - low + 1));
// expand in both directions
low--, high++;
}
}
// Function to find all unique palindromic substrings of given string
void allPalindromicSubstrings(string str)
{
// create an empty set to store all unique palindromic substrings
unordered_set<string> set;
for (int i = 0; i < str.length(); i++)
{
// find all odd length palindrome with str[i] as mid point
expand(str, i, i, set);
// find all even length palindrome with str[i] and str[i+1] as
// its mid points
expand(str, i, i + 1, set);
}
// print all unique palindromic substrings
for (auto i : set)
cout << i << " ";
}
int main()
{
string str = "google";
allPalindromicSubstrings(str);
return 0;
}
Example 5: reads the string in then determines if the string is a palindrome.
using namespace std;
// Recursive function to check if str[low..high] is a palindrome or not
bool isPalindrome(string str, int low, int high)
{
// base case
if (low >= high)
return true;
// return false if mismatch happens
if (str[low] != str[high])
return false;
// move to next the pair
return isPalindrome(str, low + 1, high - 1);
}
int main()
{
string str = "XYBYBYX";
int len = str.length();
if (isPalindrome(str, 0, len - 1))
cout << "Palindrome";
else
cout << "Not Palindrome";
return 0;
}