Given a string str, the task is to print longest palindrome word present in the string str.
Examples:
Input : Madam Arora teaches Malayalam
Output: Malayalam
Explanation: The string contains three palindrome words (i.e., Madam, Arora, Malayalam) but the length of Malayalam is greater than the other two.
Input : Welcome to GeeksforGeeks
Output : No Palindrome Word
Explanation:The string does not contain any palindrome word so the output is No Palindrome Word.
Approach:
- longestPalin() function finds the longest palindrome word by extracting every word of the string and passing it to checkPalin() function. An extra space is added in the original string to extract last word.
- checkPalin() function checks if the word is palindrome. It returns true if word is palindrome else returns false. It makes sure that empty strings are not counted as palindrome as the user may enter more than one spaces in between or at the beginning of the string.
C++
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
bool checkPalin(string word)
{
int n = word.length();
transform(word.begin(), word.end(),
word.begin(), :: tolower );
for ( int i = 0; i < n; i++, n--)
if (word[i] != word[n - 1])
return false ;
return true ;
}
string longestPalin(string str)
{
str = str + " " ;
string longestword = "" , word = "" ;
int length, length1 = 0;
for ( int i = 0; i < str.length(); i++)
{
char ch = str[i];
if (ch != ' ' )
word = word + ch;
else {
length = word.length();
if (checkPalin(word) &&
length > length1)
{
length1 = length;
longestword = word;
}
word = "" ;
}
}
return longestword;
}
int main()
{
string s = "My name is ava and i love"
" Geeksforgeeks" ;
if (longestPalin(s) == "" )
cout<< "No Palindrome" << " Word" ;
else
cout<<longestPalin(s);
return 0;
}
|
Java
public class GFG {
static boolean checkPalin(String word)
{
int n = word.length();
word = word.toLowerCase();
for ( int i = 0 ; i < n; i++, n--)
if (word.charAt(i) !=
word.charAt(n - 1 ))
return false ;
return true ;
}
static String longestPalin(String str)
{
str = str + " " ;
String longestword = "" , word = "" ;
int length, length1 = 0 ;
for ( int i = 0 ; i < str.length(); i++)
{
char ch = str.charAt(i);
if (ch != ' ' )
word = word + ch;
else {
length = word.length();
if (checkPalin(word) &&
length > length1)
{
length1 = length;
longestword = word;
}
word = "" ;
}
}
return longestword;
}
public static void main(String args[])
{
String s = new String( "My name is ava "
+ "and i love Geeksforgeeks" );
if (longestPalin(s) == "" )
System.out.println( "No Palindrome"
+ " Word" );
else
System.out.println(longestPalin(s));
}
}
|
Python3
def checkPalin(word):
n = len (word)
word = word.lower()
for i in range ( n):
if (word[i] ! = word[n - 1 ]):
return False
n - = 1
return True
def longestPalin( str ):
str = str + " "
longestword = ""
word = ""
length1 = 0
for i in range ( len ( str )):
ch = str [i]
if (ch ! = ' ' ):
word = word + ch
else :
length = len (word)
if (checkPalin(word) and
length > length1):
length1 = length
longestword = word
word = ""
return longestword
if __name__ = = "__main__" :
s = "My name is ava and i love Geeksforgeeks"
if (longestPalin(s) = = ""):
print ( "No Palindrome Word" )
else :
print (longestPalin(s))
|
Javascript
<script>
function checkPalin(word)
{
let n = word.length;
word = word.toLowerCase();
for (let i = 0; i < n; i++, n--)
if (word[i] !=
word[n-1])
return false ;
return true ;
}
function longestPalin(str)
{
str = str + " " ;
let longestword = "" , word = "" ;
let length, length1 = 0;
for (let i = 0; i < str.length; i++)
{
let ch = str[i];
if (ch != ' ' )
word = word + ch;
else {
length = word.length;
if (checkPalin(word) &&
length > length1)
{
length1 = length;
longestword = word;
}
word = "" ;
}
}
return longestword;
}
let s= "My name is ava "
+ "and i love Geeksforgeeks" ;
if (longestPalin(s) == "" )
document.write( "No Palindrome"
+ " Word" );
else
document.write(longestPalin(s));
</script>
|
C#
using System;
class GFG
{
static bool checkPalin( string word)
{
int n = word.Length;
word = word.ToLower();
for ( int i = 0; i < n; i++, n--)
if (word[i] != word[n - 1])
return false ;
return true ;
}
static string longestPalin( string str)
{
str = str + " " ;
string longestword = "" , word = "" ;
int length, length1 = 0;
for ( int i = 0; i < str.Length; i++)
{
char ch = str[i];
if (ch != ' ' )
word = word + ch;
else {
length = word.Length;
if (checkPalin(word) &&
length > length1)
{
length1 = length;
longestword = word;
}
word = "" ;
}
}
return longestword;
}
public static void Main()
{
string s = "My name is ava and i"
+ " love Geeksforgeeks" ;
if (longestPalin(s) == "" )
Console.Write( "No Palindrome Word" );
else
Console.Write(longestPalin(s));
}
}
|
Time complexity : O(n^2)
Space complexity : O(n)
Method #2:Using sorted() method in Python:
- The idea is to split the words of the string into a list .
- Traverse the list and append all palindromic words to new list
- Sort the newlist in increasing order of length of words using the sorted() method.
- Finally, print the last string present in the list.
Below is the implementation of the above approach.:
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool isPalindrome(string s) {
return s == string(s.rbegin(), s.rend());
}
void largestPalin(vector<string> s) {
vector<string> newlist;
for (string word : s) {
if (isPalindrome(word)) {
newlist.push_back(word);
}
}
sort(newlist.begin(), newlist.end(), [](string a, string b) { return a.size() < b.size(); });
cout << newlist.back() << endl;
}
int main() {
string str = "My name is ava and i love Geeksforgeeks" ;
vector<string> words;
string word;
for ( char c : str) {
if (c == ' ' ) {
words.push_back(word);
word.clear();
} else {
word += c;
}
}
if (!word.empty()) {
words.push_back(word);
}
largestPalin(words);
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static boolean isPalindrome(String s)
{
return s.equals(
new StringBuilder(s).reverse().toString());
}
public static void largestPalin(ArrayList<String> s)
{
ArrayList<String> newlist = new ArrayList<>();
for (String word : s) {
if (isPalindrome(word)) {
newlist.add(word);
}
}
Collections.sort(newlist,
(a, b) -> a.length() - b.length());
System.out.println(newlist.get(newlist.size() - 1 ));
}
public static void main(String[] args)
{
String str
= "My name is ava and i love Geeksforgeeks" ;
ArrayList<String> words = new ArrayList<>();
StringBuilder word = new StringBuilder();
for ( char c : str.toCharArray()) {
if (c == ' ' ) {
words.add(word.toString());
word.setLength( 0 );
}
else {
word.append(c);
}
}
if (word.length() > 0 ) {
words.add(word.toString());
}
largestPalin(words);
}
}
|
Python3
def ispalindrome(string):
if (string = = string[:: - 1 ]):
return True
else :
return False
def largestPalin(s):
newlist = []
for i in s:
if (ispalindrome(i)):
newlist.append(i)
s = sorted (newlist, key = len )
print (s[ len (s) - 1 ])
if __name__ = = "__main__" :
s = "My name is ava and i love Geeksforgeeks"
l = list (s.split( " " ))
largestPalin(l)
|
Javascript
<script>
function ispalindrome(string){
let temp = string
temp = temp.split( '' ).reverse().join( '' )
if (string == temp)
return true
else
return false
}
function largestPalin(s){
let newlist = []
for (let i of s){
if (ispalindrome(i))
newlist.push(i)
}
newlist.sort((a,b)=>a.length - b.length)
s = newlist
document.write(s[s.length-1], "</br>" )
}
let s = "My name is ava and i love Geeksforgeeks"
let l = s.split( " " )
largestPalin(l)
</script>
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class Program {
public static bool IsPalindrome( string s) {
return s.Equals( new string (s.Reverse().ToArray()));
}
public static void LargestPalin(List < string > s) {
List < string > newList = new List < string > ();
foreach ( string word in s) {
if (IsPalindrome(word)) {
newList.Add(word);
}
}
newList.Sort((a, b) => a.Length - b.Length);
Console.WriteLine(newList[newList.Count - 1]);
}
public static void Main( string [] args) {
string str = "My name is ava and i love Geeksforgeeks" ;
List < string > words = new List < string > ();
System.Text.StringBuilder word = new System.Text.StringBuilder();
foreach ( char c in str) {
if (c == ' ' ) {
words.Add(word.ToString());
word.Clear();
} else {
word.Append(c);
}
}
if (word.Length > 0) {
words.Add(word.ToString());
}
LargestPalin(words);
}
}
|
Output:
ava
Method #3:Using filter() method in Python:
- First, the string is converted into a list of words using the re module.
- Then the filter function is applied to the list of word to, using ispalindrome function to filter out only the palindrome words.
- After max, the function is applied using the len as key to get a word with max length
C++
#include <algorithm>
#include <iostream>
#include <regex>
#include <string>
using namespace std;
bool ispalindrome(string word)
{
return word == string(word.rbegin(), word.rend());
}
void largestPalin(string s)
{
regex pattern(R "(\b\w+\b)" );
vector<string> words(
sregex_token_iterator(s.begin(), s.end(), pattern),
sregex_token_iterator());
words.erase(remove_if(words.begin(), words.end(),
[](string word) {
return !ispalindrome(word);
}),
words.end());
auto it = max_element(
words.begin(), words.end(), [](string a, string b) {
return a.length() < b.length();
});
cout << *it << endl;
}
int main()
{
string s = "My name is ava and i love Geeksforgeeks" ;
largestPalin(s);
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static boolean isPalindrome(String word)
{
return word.equals(
new StringBuilder(word).reverse().toString());
}
public static void largestPalin(String s)
{
String[] words = s.split( "\\W+" );
List<String> palindromeWords = new ArrayList<>();
for (String word : words) {
if (isPalindrome(word)) {
palindromeWords.add(word);
}
}
String largestPalindrome
= palindromeWords.stream()
.max((a, b)
-> Integer.compare(a.length(),
b.length()))
.orElse( null );
System.out.println(largestPalindrome);
}
public static void main(String[] args)
{
String s
= "My name is ava and i love Geeksforgeeks" ;
largestPalin(s);
}
}
|
Python3
import re
def ispalindrome(word):
return word = = word[:: - 1 ]
def largestPalin(s):
words = re.findall(r '\b\w+\b' , s)
palindrome_words = filter (ispalindrome, words)
largest_palindrome = max (palindrome_words, key = len )
print (largest_palindrome)
if __name__ = = "__main__" :
s = "My name is ava and i love Geeksforgeeks"
largestPalin(s)
|
Javascript
function isPalindrome(word) {
return word === word.split( '' ).reverse().join( '' );
}
function largestPalin(s) {
const words = s.match(/\b\w+\b/g);
const palindromeWords = words.filter(isPalindrome);
const largestPalindrome = palindromeWords.reduce((a, b) => a.length >= b.length ? a : b, "" );
console.log(largestPalindrome);
}
const s = "My name is ava and i love Geeksforgeeks" ;
largestPalin(s);
|
C#
using System;
using System.Linq;
class Program {
static bool IsPalindrome( string word)
{
return word.SequenceEqual(word.Reverse());
}
static string LargestPalin( string s)
{
var words = s.Split(
new char [] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
var palindromeWords = words.Where(IsPalindrome);
var largestPalindrome
= palindromeWords
.OrderByDescending(word = > word.Length)
.FirstOrDefault();
return largestPalindrome;
}
static void Main( string [] args)
{
string s
= "My name is ava and i love Geeksforgeeks" ;
string largestPalindrome = LargestPalin(s);
Console.WriteLine(largestPalindrome);
}
}
|
Time complexity:O(n)
Auxiliary Space:O(n)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
11 Apr, 2023
Like Article
Save Article