Dada una string S de longitud N y una array Q[][] de consultas en la forma {l, r, y} . Para cada consulta, la tarea es imprimir el número de caracteres y presentes en el rango [l, r] .
Ejemplos:
Entrada: S = “aabv”, Q[][] = {{0, 3, ‘a’}, {1, 2, ‘b’}}
Salida: 2 1
Explicación:
Consulta 1: Número de carácter ‘a’ presente en el rango [0, 3] es 2.
Consulta 2: Número de carácter ‘b’ presente en el rango [1, 2] es 1.Entrada: S = “abcd”, Q[][] = {{1, 3, ‘c’}, {1, 1, ‘b’}}
Salida: 1 1
Explicación:
Consulta 1: Número de carácter ‘c’ presente en el rango [1, 3] es 1.
Consulta 2: Número de carácter ‘b’ presente en el rango [1, 1] es 1.
Enfoque ingenuo: el enfoque más simple es atravesar la string sobre el rango [l, r] e incrementar el contador en 1 si el carácter en el índice i es igual a y para cada consulta {l, r, y} . Después de atravesar, imprima el contador para cada consulta.
Complejidad temporal: O(N*Q)
Espacio auxiliar: O(N)
Enfoque eficiente: la idea es precalcular la cantidad de caracteres presentes en el rango de 1 a i para cada carácter de ‘a’ a ‘z’ donde 1 ≤ i ≤ N utilizando la técnica Prefix Sum . Siga los pasos a continuación para resolver el problema:
- Inicialice una array dp[N+1][26] donde dp[i][j] almacena la cantidad de caracteres (i+’a’) presentes en el rango [0, i] .
- Ahora, calcule previamente el número de cada carácter presente en el rango [1, i] donde 1 ≤ i ≤ N incrementando dp[i][j] por dp[i – 1][j] donde 0 ≤ j < 26 e incrementando dp[i][S[j] – ‘a’] por 1 .
- Para cada consulta {l, r, y} , imprima el valor de dp[r][y – ‘a’] – dp[l – 1][y – ‘a’] como el número de caracteres y presentes en el rango [l, r] .
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 count of char // y present in the range [l, r] void noOfChars(string s, char queries[][3], int q) { // Length of the string int n = s.length(); // Stores the precomputed results int dp[n + 1][26]; memset(dp, 0, sizeof(dp)); // Iterate the given string for(int i = 0; i < n; i++) { // Increment dp[i][y-'a'] by 1 dp[i + 1][s[i]-'a']++; // Pre-compute for(int j = 0; j < 26; j++) { dp[i + 1][j] += dp[i][j]; } } // Traverse each query for(int i = 0; i < q; i++) { int l = (int)queries[i][0]; int r = (int)queries[i][1]; int c = queries[i][2] - 'a'; // Print the result for // each query cout << dp[r] - dp[l - 1] << " "; } } // Driver Code int main() { // Given string string S = "aabv"; // Given Queries char queries[2][3] = {{ 1, 2, 'a' },{ 2, 3, 'b' }}; // Function Call noOfChars(S, queries, 2); return 0; } // This code is contributed by avanitrachhadiya2155
Java
// Java program for the above approach import java.io.*; class GFG { // Function to print count of char // y present in the range [l, r] static void noOfChars(String s, char[][] queries) { // Length of the string int n = s.length(); // Stores the precomputed results int dp[][] = new int[n + 1][26]; // Iterate the given string for (int i = 0; i < n; i++) { // Increment dp[i][y-'a'] by 1 dp[i + 1][s.charAt(i) - 'a']++; // Pre-compute for (int j = 0; j < 26; j++) { dp[i + 1][j] += dp[i][j]; } } // Number of queries int q = queries.length; // Traverse each query for (int i = 0; i < q; i++) { int l = (int)queries[i][0]; int r = (int)queries[i][1]; int c = queries[i][2] - 'a'; // Print the result for // each query System.out.print( dp[r] - dp[l - 1] + " "); } } // Driver Code public static void main(String[] args) { // Given string String S = "aabv"; // Given Queries char queries[][] = new char[][] { { 1, 2, 'a' }, { 2, 3, 'b' } }; // Function Call noOfChars(S, queries); } }
Python3
# Python3 program for the above approach # Function to print count of char # y present in the range [l, r] def noOfChars(s, queries): # Length of the string n = len(s) # Stores the precomputed results dp = [[0 for i in range(26)] for i in range(n + 1)] # Iterate the given string for i in range(n): # Increment dp[i][y-'a'] by 1 dp[i + 1][ord(s[i]) - ord('a')] += 1 # Pre-compute for j in range(26): dp[i + 1][j] += dp[i][j] # Number of queries q = len(queries) # Traverse each query for i in range(q): l = queries[i][0] r = queries[i][1] c = ord(queries[i][2]) - ord('a') # Print the result for # each query print(dp[r] - dp[l - 1], end = " ") # Driver Code if __name__ == '__main__': # Given string S = "aabv" # Given Queries queries = [ [ 1, 2, 'a' ], [ 2, 3, 'b' ] ] # Function Call noOfChars(S, queries) # This code is contributed by mohit kumar 29
C#
// C# program for the above approach using System; public class GFG { // Function to print count of char // y present in the range [l, r] static void noOfChars(String s, char[,] queries) { // Length of the string int n = s.Length; // Stores the precomputed results int [,]dp = new int[n + 1, 26]; // Iterate the given string for (int i = 0; i < n; i++) { // Increment dp[i,y-'a'] by 1 dp[i + 1, s[i] - 'a']++; // Pre-compute for (int j = 0; j < 26; j++) { dp[i + 1, j] += dp[i, j]; } } // Number of queries int q = queries.GetLength(0); // Traverse each query for (int i = 0; i < q; i++) { int l = (int)queries[i, 0]; int r = (int)queries[i, 1]; int c = queries[i, 2] - 'a'; // Print the result for // each query Console.Write( dp[r, c] - dp[l - 1, c] + " "); } } // Driver Code public static void Main(String[] args) { // Given string String S = "aabv"; // Given Queries char [,]queries = new char[,] { { (char)1, (char)2, 'a' }, { (char)2, (char)3, 'b' } }; // Function Call noOfChars(S, queries); } } // This code is contributed by 29AjayKumar
Javascript
<script> // JavaScript program for the above approach // Function to print count of char // y present in the range [l, r] function noOfChars(s,queries) { // Length of the string var n = s.length; // Stores the precomputed results var dp = Array(n+1).fill(0).map(x => Array(26).fill(0)); // Iterate the given string for (var i = 0; i < n; i++) { // Increment dp[i][y-'a'] by 1 dp[i + 1][s.charAt(i).charCodeAt(0) - 'a'.charCodeAt(0)]++; // Pre-compute for (var j = 0; j < 26; j++) { dp[i + 1][j] += dp[i][j]; } } // Number of queries var q = queries.length; // Traverse each query for (var i = 0; i < q; i++) { var l = String.fromCharCode(queries[i][0]).charCodeAt(0); var r = String.fromCharCode(queries[i][1]).charCodeAt(0); var c = queries[i][2].charCodeAt(0) - 'a'.charCodeAt(0); // Print the result for // each query document.write( dp[r] - dp[l - 1] + " "); } } // Driver Code // Given string var S = "aabv"; // Given Queries var queries = [ [ 1, 2, 'a' ], [ 2, 3, 'b' ] ]; // Function Call noOfChars(S, queries); // This code contributed by shikhasingrajput </script>
2 1
Complejidad temporal: O(Q+N*26)
Espacio auxiliar: O(N)
Publicación traducida automáticamente
Artículo escrito por akshitdiwan05 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA