Find all Palindrome Strings in given Array of strings - GeeksforGeeks

08 Mar, 2022
Given an array of strings arr[] of size N where each string consists only of lowercase English letter. The task is to find all palindromic string in the array. Print -1 if no palindrome is present in the given array.
Examples:
Input: arr[] = {“abc”, “car”, “ada”, “racecar”, “cool”}Output: “ada”, “racecar”Explanation: These two are the only palindrome strings in the given array
Input: arr[] = {“def”, “ab”}Output: -1Explanation: No palindrome string is present in the given array.
Approach: The solution is based on greedy approach. Check every string of an array if it is palindrome or not and also keep track of the all palindrome string. Follow the steps below to solve the problem:
Initialize a vector of string ans.
Iterate over the range [0, N) using the variable i and If arr[i] is a palindrome, then add it to the ans.
After performing the above steps, print the strings present in ans as the resultant strings.
Below is the implementation of the above approach.
C++
Java
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if given string// is Palindrome or notbool isPalindrome(string& s){    // Copy string s char into string a    string a = s;    reverse(s.begin(), s.end());     // Check if two string are equal or not    return s == a;} // Function to return all Palindrome stringvector<string> PalindromicStrings(string arr[],                                  int N){    vector<string> ans;     // Loop to find palindrome string    for (int i = 0; i < N; i++) {         // Checking if given string is        // palindrome or not        if (isPalindrome(arr[i])) {             // Update answer variable            ans.push_back(arr[i]);        }    }    return ans;} // Driver Codeint main(){     string arr[]        = { "abc", "car", "ada", "racecar", "cool" };    int N = sizeof(arr) / sizeof(arr[0]);     // Print required answer    vector<string> s = PalindromicStrings(arr, N);    if(s.size() == 0)        cout << "-1";    for(string st: s)        cout << st << " ";     return 0;}
// Java code to find the maximum median// of a sub array having length at least K.import java.util.*;public class GFG{       // Function to check if given string  // is Palindrome or not  static boolean isPalindrome(String str)  {         // Start from leftmost and rightmost corners of str    int l = 0;    int h = str.length() - 1;     // Keep comparing characters while they are same    while (h > l)    {      if (str.charAt(l++) != str.charAt(h--))      {        return false;      }    }    return true;  }   // Function to return all Palindrome string  static ArrayList<String> PalindromicStrings(String []arr,                                      int N)  {    ArrayList<String> ans = new ArrayList<String>();     // Loop to find palindrome string    for (int i = 0; i < N; i++) {       // Checking if given string is      // palindrome or not      if (isPalindrome(arr[i])) {         // Update answer variable        ans.add(arr[i]);      }    }    return ans;  }   // Driver Code  public static void main(String args[])  {     String []arr      = { "abc", "car", "ada", "racecar", "cool" };    int N = arr.length;     // Print required answer    ArrayList<String> s = PalindromicStrings(arr, N);    if(s.size() == 0)      System.out.print("-1");    for (String st : s)      System.out.print(st + " ");   }} // This code is contributed by Samim Hossain Mondal.
// C# program for the above approachusing System;using System.Collections;class GFG{     // Function to check if given string  // is Palindrome or not  static bool isPalindrome(string str)  {         // Start from leftmost and rightmost corners of str    int l = 0;    int h = str.Length - 1;     // Keep comparing characters while they are same    while (h > l)    {      if (str[l++] != str[h--])      {        return false;      }    }    return true;  }   // Function to return all Palindrome string  static ArrayList PalindromicStrings(string []arr,                                      int N)  {    ArrayList ans = new ArrayList();     // Loop to find palindrome string    for (int i = 0; i < N; i++) {       // Checking if given string is      // palindrome or not      if (isPalindrome(arr[i])) {         // Update answer variable        ans.Add(arr[i]);      }    }    return ans;  }   // Driver Code  public static void Main()  {     string []arr      = { "abc", "car", "ada", "racecar", "cool" };    int N = arr.Length;     // Print required answer    ArrayList s = PalindromicStrings(arr, N);    if(s.Count == 0)      Console.Write("-1");    foreach(string st in s)      Console.Write(st + " ");   }}// This code is contributed by Samim Hossain Mondal.
<script> // JavaScript code for the above approach  // Function to check if given string// is Palindrome or notfunction isPalindrome(s){    // Copy string s char into string a    let a = s;    s = s.split('').reverse().join('');     // Check if two string are equal or not    return s == a;} // Function to return all Palindrome stringfunction PalindromicStrings(arr,N){    let ans = [];     // Loop to find palindrome string    for (let i = 0; i < N; i++) {         // Checking if given string is        // palindrome or not        if (isPalindrome(arr[i])) {             // Update answer variable            ans.push(arr[i]);        }    }    return ans;} // Driver Codelet arr = [ "abc", "car", "ada", "racecar", "cool" ];let N = arr.length; // Print required answerlet s = PalindromicStrings(arr, N);if(s.length == 0)    document.write("-1");for(let st of s)    document.write(st," "); // This code is contributed by shinjanpatra</script>
ada racecar 
 Time complexity: O(N * W) where W is the average length of the stringsAuxiliary Space: O(N * W) 
samim2000
varshagumber28
kk9826225
kk773572498
simranarora5sos
shinjanpatra
Algo-Geek 2021
palindrome
Algo Geek
Strings
Strings
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Count of operation required to water all the plants
Lexicographically smallest string formed by concatenating any prefix and its mirrored form
Divide given number into two even parts
Check if the given string is valid English word or not
Check if an edge is a part of any Minimum Spanning Tree
Reverse a string in Java
Write a program to reverse an array or string
C++ Data Types
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string