Dada una string str y un entero K , la tarea es verificar si está compuesta por K caracteres alternos.
Ejemplos:
Entrada: str = “acdeac”, K = 4
Salida: Sí
Entrada: str = “abcdcab”, K = 2
Salida: No
Enfoque: Para que la string se componga de K caracteres alternos, debe cumplir las siguientes condiciones:
- Todos los caracteres en los índices (i + mK) deben ser iguales, donde i es el índice actual y mK representa el m enésimo múltiplo de K. Significa que después de cada índice K, el carácter debe repetirse.
- Los caracteres adyacentes no deben ser iguales. Esto se debe a que si la string es del tipo «AAAAA», donde un solo carácter se repite cualquier cantidad de veces, la condición anterior se cumplirá, pero la respuesta debe ser ‘No’ en este caso.
El siguiente código es la implementación del enfoque anterior:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to check if a string // is made up of k alternating characters bool isKAlternating(string s, int k) { if (s.length() < k) return false; int checker = 0; // Check if all the characters at // indices 0 to K-1 are different for (int i = 0; i < k; i++) { int bitAtIndex = s[i] - 'a'; // If that bit is already set in // checker, return false if ((checker & (1 << bitAtIndex)) > 0) { return false; } // Otherwise update and continue by // setting that bit in the checker checker = checker | (1 << bitAtIndex); } for (int i = k; i < s.length(); i++) if (s[i - k] != s[i]) return false; return true; } // Driver code int main() { string str = "acdeac"; int K = 4; if (isKAlternating(str, K)) cout << "Yes" << endl; else cout << "No" << endl; return 0; }
Java
// Java implementation of the approach class GFG{ // Function to check if a String // is made up of k alternating characters static boolean isKAlternating(String s, int k) { if (s.length() < k) return false; int checker = 0; // Check if all the characters at // indices 0 to K-1 are different for (int i = 0; i < k; i++) { int bitAtIndex = s.charAt(i) - 'a'; // If that bit is already set in // checker, return false if ((checker & (1 << bitAtIndex)) > 0) { return false; } // Otherwise update and continue by // setting that bit in the checker checker = checker | (1 << bitAtIndex); } for (int i = k; i < s.length(); i++) if (s.charAt(i - k) != s.charAt(i) ) return false; return true; } // Driver code public static void main(String[] args) { String str = "acdeac"; int K = 4; if (isKAlternating(str, K)) System.out.print("Yes" +"\n"); else System.out.print("No" +"\n"); } } // This code is contributed by sapnasingh4991
Python3
# Python 3 implementation of the approach # Function to check if a string # is made up of k alternating characters def isKAlternating( s, k): if (len(s) < k): return False checker = 0 # Check if all the characters at # indices 0 to K-1 are different for i in range( k): bitAtIndex = ord(s[i]) - ord('a') # If that bit is already set in # checker, return false if ((checker & (1 << bitAtIndex)) > 0): return False # Otherwise update and continue by # setting that bit in the checker checker = checker | (1 << bitAtIndex) for i in range(k,len(s)): if (s[i - k] != s[i]): return False return True # Driver code if __name__ =="__main__": st = "acdeac" K = 4 if (isKAlternating(st, K)): print ("Yes") else: print ("No") # This code is contributed by chitranayal
C#
// C# implementation of the approach using System; class GFG{ // Function to check if a String // is made up of k alternating characters static bool isKAlternating(String s, int k) { if (s.Length < k) return false; int checker = 0; // Check if all the characters at // indices 0 to K-1 are different for (int i = 0; i < k; i++) { int bitAtIndex = s[i] - 'a'; // If that bit is already set in // checker, return false if ((checker & (1 << bitAtIndex)) > 0) { return false; } // Otherwise update and continue by // setting that bit in the checker checker = checker | (1 << bitAtIndex); } for (int i = k; i < s.Length; i++) if (s[i - k] != s[i] ) return false; return true; } // Driver code public static void Main() { String str = "acdeac"; int K = 4; if (isKAlternating(str, K)) Console.WriteLine("Yes"); else Console.WriteLine("No"); } } // This article contributed by AbhiThakur
Javascript
<script> // Javascript implementation of the approach // Function to check if a string // is made up of k alternating characters function isKAlternating(s, k) { if (s.length < k) return false; var checker = 0; // Check if all the characters at // indices 0 to K-1 are different for (var i = 0; i < k; i++) { var bitAtIndex = s[i].charCodeAt(0) - 'a'.charCodeAt(0); // If that bit is already set in // checker, return false if ((checker & (1 << bitAtIndex)) > 0) { return false; } // Otherwise update and continue by // setting that bit in the checker checker = checker | (1 << bitAtIndex); } for (var i = k; i < s.length; i++) if (s[i - k] != s[i]) return false; return true; } // Driver code var str = "acdeac"; var K = 4; if (isKAlternating(str, K)) document.write( "Yes" ); else document.write( "No" ); // This code is contributed by importantly. </script>
Producción:
Yes
- Complejidad de tiempo: O(N)
Publicación traducida automáticamente
Artículo escrito por muskan_garg y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA