Dada una array de strings arr[] de tamaño N donde cada string consta solo de letras minúsculas en inglés. La tarea es encontrar todas las strings palindrómicas en la array. Imprime -1 si no hay palíndromo presente en la array dada.
Ejemplos:
Entrada: arr[] = {“abc”, “car”, “ada”, “racecar”, “cool”}
Salida: “ada”, “racecar”
Explicación: Estas dos son las únicas strings palíndromo en la array dadaEntrada: arr[] = {“def”, “ab”}
Salida: -1
Explicación: No hay una string palíndromo presente en la array dada.
Enfoque: La solución se basa en el enfoque codicioso . Verifique cada string de una array si es palíndromo o no y también realice un seguimiento de todas las strings de palíndromo. Siga los pasos a continuación para resolver el problema:
- Inicialice un vector de string ans .
- Iterar sobre el rango [0, N) usando la variable i y Si arr[i] es un palíndromo, entonces agréguelo a ans .
- Después de realizar los pasos anteriores, imprima las strings presentes en ans como las strings resultantes.
A continuación se muestra la implementación del enfoque anterior.
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to check if given string // is Palindrome or not bool 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 string vector<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 Code int 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
// 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.
Python3
# Python program for the above approach: ## Function to check if given string ## is Palindrome or not def isPalindrome(s): ## Copy string s char into string a a = "" for ch in s: a += ch s = "".join(reversed(s)) ## Check if two string are equal or not return s == a ## Function to return all Palindrome string def PalindromicStrings(arr, N): ans = [] ## Loop to find palindrome string for i in range(N): ## Checking if given string is ## palindrome or not if (isPalindrome(arr[i])): ## Update answer variable ans.append(arr[i]); return ans ## Driver code if __name__ == '__main__': arr = ["abc", "car", "ada", "racecar", "cool" ] N = len(arr) ## Print required answer s = PalindromicStrings(arr, N); if(len(s) == 0): print(-1, end="") for st in s: print(st, end=" ") # This code is contributed by subhamgoyal2014.
C#
// C# program for the above approach using 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.
Javascript
<script> // JavaScript code for the above approach // Function to check if given string // is Palindrome or not function 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 string function 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 Code let arr = [ "abc", "car", "ada", "racecar", "cool" ]; let N = arr.length; // Print required answer let 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
Complejidad temporal: O(N * W) donde W es la longitud media de las strings
Espacio auxiliar: O(N * W)