Find occurrences of palindrome words in a string star_border
Write a function which given a string, count and return the palindrome words present in the string. A word in a string is separated with space(s).
Sample Input 1
Mom and Dad are my best friends
Sample Output 1
2
Explanation 1
Thisstring contains two palindromewords (i.e., Mom, Dad) so the countis 2.
Sample Input 2
mohit speaks english
Sample Output 2
0
Explanation 2
This string contains no palindrome words.
static int countPalindrome(String str) {
// Write your code here
String[] words = str.split(" ");
int count =0;
for(String word:words)
{
if(palindrome(word))
{
count++;
}
}
return count;
}
static boolean palindrome(String word)
{
int s = 0;
int e = word.length()-1;
while(s<e)
{
if(Character.toLowerCase(word.charAt(s))!=Character.toLowerCase(word.charAt(e)))
{
return false;
}
s++;
e--;
}
return true;
}