Function of palindrome in string code example
Example 1: Write a function that tests whether a string is a palindrome
def palindrome_check(string):
string = list(string)
tmp = []
#remove any spaces
for x in range(0, len(string)):
if(string[x] != " "):
tmp.append(string[x].lower())
#now reverse the string
array1 = []
i = 0
j = len(tmp)-1
while(i < len(tmp)):
array1.append(tmp[j])
i += 1
j -= 1
#check if array1 is equal to the string
counter = 0
for x in range(0, len(tmp)):
if(tmp[x] == array1[x]):
counter += 1
#if the counter is equal to the length of the string then the word
#is the same
if(counter == len(tmp)):
return True
return False
Example 2: find all the palindrome substring in a given string
#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
void expand(string str, int low, int high, auto &set)
{
while (low >= 0 && high < str.length()
&& str[low] == str[high])
{
set.insert(str.substr(low, high - low + 1));
low--, high++;
}
}
void allPalindromicSubstrings(string str)
{
unordered_set<string> set;
for (int i = 0; i < str.length(); i++)
{
expand(str, i, i, set);
expand(str, i, i + 1, set);
}
for (auto i : set)
cout << i << " ";
}
int main()
{
string str = "google";
allPalindromicSubstrings(str);
return 0;
}