Dada una string S que consta de N caracteres, la tarea es imprimir todas las strings palindrómicas de longitud 3 en orden lexicográfico que se pueden formar usando caracteres de la string S dada .
Ejemplos:
Entrada: S = “aabc”
Salida:
aba
acaEntrada: S = “ddadbac”
Salida:
aba
aca
ada
papá
dbd
dcd
ddd
Enfoque: El problema dado se puede resolver usando el concepto de Hashing , implementándolo usando un Mapa para almacenar el conteo de caracteres. Siga los pasos a continuación para resolver el problema:
- Inicialice un mapa_desordenado , digamos Hash , que almacene el conteo de cada carácter.
- Almacene la frecuencia de cada carácter de la string en el mapa Hash .
- Inicialice un Conjunto de strings, digamos st , para almacenar todas las strings palindrómicas de longitud 3 .
- Itere sobre los caracteres [a, z] , usando una variable i , y realice los siguientes pasos:
- Si el valor de Hash[i] es 2 , itere sobre los caracteres en el rango [a, z] , usando una variable j . Si el valor de Hash[j] es mayor que 0 e i no es igual a j , inserte la string (i + j + i) en Set st .
- De lo contrario, si el valor de Hash[i] es mayor que 2 , itere sobre los caracteres en el rango [a, z] usando una variable j y si el valor de Hash[j] es mayor que 0 , luego inserte la string ( i + j + i) en el conjunto st .
- Después de completar los pasos anteriores, recorra el punto establecido e imprima la string almacenada en él.
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 print all palindromic // strings of length 3 that can be // formed using characters of string S void generatePalindrome(string S) { // Stores the count of character unordered_map<char, int> Hash; // Traverse the string S for (auto ch : S) { Hash[ch]++; } // Stores all palindromic strings set<string> st; // Iterate over the charchaters // over the range ['a', 'z'] for (char i = 'a'; i <= 'z'; i++) { // If Hash[ch] is equal to 2 if (Hash[i] == 2) { // Iterate over the characters // over the range ['a', 'z'] for (char j = 'a'; j <= 'z'; j++) { // Stores all the // palindromic string string s = ""; if (Hash[j] && i != j) { s += i; s += j; s += i; // Push the s into // the set st st.insert(s); } } } // If Hash[i] is greater than // or equal to 3 if (Hash[i] >= 3) { // Iterate over charchaters // over the range ['a', 'z'] for (char j = 'a'; j <= 'z'; j++) { // Stores all the // palindromic string string s = ""; // If Hash[j] is positive if (Hash[j]) { s += i; s += j; s += i; // Push s into // the set st st.insert(s); } } } } // Iterate over the set for (auto ans : st) { cout << ans << "\n"; } } // Driver Code int main() { string S = "ddabdac"; generatePalindrome(S); return 0; }
Java
// Java program for the above approach import java.util.*; public class Main { // Function to print all palindromic // strings of length 3 that can be // formed using characters of string S static void generatePalindrome(String S) { // Stores the count of character HashMap<Character, Integer> Hash = new HashMap<>(); // Traverse the string S for(int i = 0; i < S.length(); i++) { if (Hash.containsKey(S.charAt(i))) Hash.put(S.charAt(i), Hash.get(S.charAt(i))+1); else Hash.put(S.charAt(i), 1); } // Stores all palindromic strings TreeSet<String> st = new TreeSet<String>(); // Iterate over the charchaters // over the range ['a', 'z'] for(char i = 'a'; i <= 'z'; i++) { // If Hash[ch] is equal to 2 if (Hash.containsKey(i) && Hash.get(i) == 2) { // Iterate over the characters // over the range ['a', 'z'] for(char j = 'a'; j <= 'z'; j++) { // Stores all the // palindromic string String s = ""; if (Hash.containsKey(j) && i != j) { s += i; s += j; s += i; // Push the s into // the set st st.add(s); } } } // If Hash[i] is greater than // or equal to 3 if (Hash.containsKey(i) && Hash.get(i) >= 3) { // Iterate over charchaters // over the range ['a', 'z'] for(char j = 'a'; j <= 'z'; j++) { // Stores all the // palindromic string String s = ""; // If Hash[j] is positive if (Hash.containsKey(j)) { s += i; s += j; s += i; // Push s into // the set st st.add(s); } } } } // Iterate over the set for(String ans : st) { System.out.println(ans); } } // Driver code public static void main(String[] args) { String S = "ddabdac"; generatePalindrome(S); } } // This code is contributed by divyesh072019.
Python3
# Python3 program for the above approach # Function to print all palindromic # strings of length 3 that can be # formed using characters of string S def generatePalindrome(S): # Stores the count of character Hash = {} # Traverse the string S for ch in S: Hash[ch] = Hash.get(ch,0) + 1 # Stores all palindromic strings st = {} # Iterate over the charchaters # over the range ['a', 'z'] for i in range(ord('a'), ord('z') + 1): # If Hash[ch] is equal to 2 if (chr(i) in Hash and Hash[chr(i)] == 2): # Iterate over the characters # over the range ['a', 'z'] for j in range(ord('a'), ord('z') + 1): # Stores all the # palindromic string s = "" if (chr(j) in Hash and i != j): s += chr(i) s += chr(j) s += chr(i) # Push the s into # the set st st[s] = 1 # If Hash[i] is greater than # or equal to 3 if ((chr(i) in Hash) and Hash[chr(i)] >= 3): # Iterate over charchaters # over the range ['a', 'z'] for j in range(ord('a'), ord('z') + 1): # Stores all the # palindromic string s = "" # If Hash[j] is positive if (chr(j) in Hash): s += chr(i) s += chr(j) s += chr(i) # Push s into # the set st st[s] = 1 # Iterate over the set for ans in st: print(ans) # Driver Code if __name__ == '__main__': S = "ddabdac" generatePalindrome(S) # This code is contributed by mohit kumar 29
C#
// C# program for the above approach using System; using System.Collections.Generic; class GFG{ // Function to print all palindromic // strings of length 3 that can be // formed using characters of string S static void generatePalindrome(string S) { // Stores the count of character Dictionary<char, int> Hash = new Dictionary<char, int>(); // Traverse the string S foreach (char ch in S) { if (Hash.ContainsKey(ch)) Hash[ch]++; else Hash.Add(ch, 1); } // Stores all palindromic strings HashSet<string> st = new HashSet<string>(); // Iterate over the charchaters // over the range ['a', 'z'] for(char i = 'a'; i <= 'z'; i++) { // If Hash[ch] is equal to 2 if (Hash.ContainsKey(i) && Hash[i] == 2) { // Iterate over the characters // over the range ['a', 'z'] for(char j = 'a'; j <= 'z'; j++) { // Stores all the // palindromic string string s = ""; if (Hash.ContainsKey(j) && i != j) { s += i; s += j; s += i; // Push the s into // the set st st.Add(s); } } } // If Hash[i] is greater than // or equal to 3 if (Hash.ContainsKey(i) && Hash[i] >= 3) { // Iterate over charchaters // over the range ['a', 'z'] for(char j = 'a'; j <= 'z'; j++) { // Stores all the // palindromic string string s = ""; // If Hash[j] is positive if (Hash.ContainsKey(j)) { s += i; s += j; s += i; // Push s into // the set st st.Add(s); } } } } // Iterate over the set foreach(string ans in st) { Console.WriteLine(ans); } } // Driver Code public static void Main() { string S = "ddabdac"; generatePalindrome(S); } } // This code is contributed by SURENDRA_GANGWAR
Javascript
<script> // Javascript program for the above approach // Function to print all palindromic // strings of length 3 that can be // formed using characters of string S function generatePalindrome(S) { // Stores the count of character let Hash=new Map(); // Traverse the string S for (let ch=0;ch< S.length;ch++) { if(!Hash.has(S[ch])) Hash.set(S[ch],1); else { Hash.set(S[ch],Hash.get(S[ch])+1) } } // Stores all palindromic strings let st=new Set(); // Iterate over the charchaters // over the range ['a', 'z'] for (let i = 'a'.charCodeAt(0); i <= 'z'.charCodeAt(0); i++) { // If Hash[ch] is equal to 2 if (Hash.get(String.fromCharCode(i)) == 2) { // Iterate over the characters // over the range ['a', 'z'] for (let j = 'a'.charCodeAt(0); j <= 'z'.charCodeAt(0); j++) { // Stores all the // palindromic string let s = ""; if (Hash.get(String.fromCharCode(j)) && i != j) { s += String.fromCharCode(i); s += String.fromCharCode(j); s += String.fromCharCode(i); // Push the s into // the set st st.add(s); } } } // If Hash[i] is greater than // or equal to 3 if (Hash.get(String.fromCharCode(i)) >= 3) { // Iterate over charchaters // over the range ['a', 'z'] for (let j = 'a'.charCodeAt(0); j <= 'z'.charCodeAt(0); j++) { // Stores all the // palindromic string let s = ""; // If Hash[j] is positive if (Hash.get(String.fromCharCode(j))) { s += String.fromCharCode(i); s += String.fromCharCode(j); s += String.fromCharCode(i); // Push s into // the set st st.add(s); } } } } // Iterate over the set for (let item of st.values()) { document.write(item+"<br>") } } // Driver Code let S = "ddabdac"; generatePalindrome(S); // This code is contributed by unknown2108 </script>
aba aca ada dad dbd dcd ddd
Complejidad de Tiempo: O(26*26)
Espacio Auxiliar: O(26)
Publicación traducida automáticamente
Artículo escrito por pundirmudit1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA