Dada una string S , la tarea es imprimir el recuento de substrings de una string dada cuyo primer y último carácter son diferentes.
Ejemplos:
Entrada: S = “abcab”
Salida: 8
Explicación:
Hay 8 substrings que tienen el primer y el último carácter diferentes {ab, abc, abcab, bc, bca, ca, cab, ab}.Entrada: S = “aba”
Salida: 2
Explicación:
Hay 2 substrings que tienen el primer y el último carácter diferentes {ab, ba}.
Enfoque ingenuo: la idea es generar todas las substrings posibles de una string determinada y, para cada substring, verificar si el primer y el último carácter son diferentes o no. Si se encuentra que es cierto, incremente el conteo en 1 y verifique la siguiente substring. Imprime el conteo después del recorrido de toda la substring.
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 count the substrings // having different first and last // characters int countSubstring(string s, int n) { // Store the final count int ans = 0; // Loop to traverse the string for (int i = 0; i < n; i++) { // Counter for each iteration int cnt = 0; // Iterate over substrings for (int j = i + 1; j < n; j++) { // Compare the characters if (s[j] != s[i]) // Increase count cnt++; } // Adding count of substrings // to the final count ans += cnt; } // Print the final count cout << ans; } // Driver Code int main() { // Given string string S = "abcab"; // Length of the string int N = 5; // Function Call countSubstring(S, N); return 0; }
Java
// Java program for the above approach import java.util.*; import java.lang.*; import java.io.*; class GFG{ // Function to count the substrings // having different first and last // characters static void countSubstring(String s, int n) { // Store the final count int ans = 0; // Loop to traverse the string for(int i = 0; i < n; i++) { // Counter for each iteration int cnt = 0; // Iterate over substrings for(int j = i + 1; j < n; j++) { // Compare the characters if (s.charAt(j) != s.charAt(i)) // Increase count cnt++; } // Adding count of substrings // to the final count ans += cnt; } // Print the final count System.out.print(ans); } // Driver Code public static void main(String[] args) { // Given string String S = "abcab"; // Length of the string int N = 5; // Function call countSubstring(S, N); } } // This code is contributed by code_hunt
Python3
# Python3 program for the above approach # Function to count the substrings # having different first and last # characters def countSubstring(s, n): # Store the final count ans = 0 # Loop to traverse the string for i in range(n): # Counter for each iteration cnt = 0 # Iterate over substrings for j in range(i + 1, n): # Compare the characters if (s[j] != s[i]): # Increase count cnt += 1 # Adding count of substrings # to the final count ans += cnt # Print the final count print(ans) # Driver Code # Given string S = "abcab" # Length of the string N = 5 # Function call countSubstring(S, N) # This code is contributed by code_hunt
C#
// C# program for the above approach using System; using System.Collections; using System.Collections.Generic; using System.Text; class GFG{ // Function to count the substrings // having different first and last // characters static void countSubstring(string s, int n) { // Store the final count int ans = 0; // Loop to traverse the string for(int i = 0; i < n; i++) { // Counter for each iteration int cnt = 0; // Iterate over substrings for(int j = i + 1; j < n; j++) { // Compare the characters if (s[j] != s[i]) // Increase count cnt++; } // Adding count of substrings // to the final count ans += cnt; } // Print the final count Console.Write(ans); } // Driver Code public static void Main(string[] args) { // Given string string S = "abcab"; // Length of the string int N = 5; // Function call countSubstring(S, N); } } // This code is contributed by rutvik_56
Javascript
<script> // JavaScript program for // the above approach // Function to count the substrings // having different first and last // characters function countSubstring(s, n) { // Store the final count let ans = 0; // Loop to traverse the string for(let i = 0; i < n; i++) { // Counter for each iteration let cnt = 0; // Iterate over substrings for(let j = i + 1; j < n; j++) { // Compare the characters if (s[j] != s[i]) // Increase count cnt++; } // Adding count of substrings // to the final count ans += cnt; } // Print the final count document.write(ans); } // Driver code // Given string let S = "abcab"; // Length of the string let N = 5; // Function call countSubstring(S, N); // This code is contributed by splevel62. </script>
8
Complejidad de Tiempo: O(N 2 )
Espacio Auxiliar: O(1)
Enfoque eficiente: el enfoque anterior se puede optimizar utilizando Map by para almacenar la frecuencia de los caracteres de la string. Siga los pasos a continuación para resolver el problema:
- Inicialice dos variables, una para contar caracteres diferentes para cada iteración (digamos cur ) y otra para almacenar el recuento final de substrings (digamos ans ).
- Inicialice un mapa M para almacenar la frecuencia de todos los caracteres en él.
- Recorra la string dada y para cada carácter, siga los pasos a continuación:
- Iterar el mapa M .
- Si el primer elemento, es decir, la clave del mapa no es la misma que el carácter actual, entonces proceda.
- De lo contrario, agregue el valor correspondiente al carácter actual.
- Después de recorrer el Mapa , agregue cur al resultado final, es decir, ans += cur .
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 count the substrings // having different first & last character int countSubstring(string s, int n) { // Stores frequency of each char map<char, int> m; // Loop to store frequency of // the characters in a Map for (int i = 0; i < n; i++) m[s[i]]++; // To store final result int ans = 0; // Traversal of string for (int i = 0; i < n; i++) { // Store answer for every // iteration int cnt = 0; m[s[i]]--; // Map traversal for (auto value : m) { // Compare current char if (value.first == s[i]) { continue; } else { cnt += value.second; } } ans += cnt; } // Print the final count cout << ans; } // Driver Code int main() { // Given string string S = "abcab"; // Length of the string int N = 5; // Function Call countSubstring(S, N); return 0; }
Java
// Java program for the above approach import java.util.*; class GFG{ // Function to count the subStrings // having different first & last character static void countSubString(char []s, int n) { // Stores frequency of each char HashMap<Character, Integer> mp = new HashMap<Character, Integer>(); // Loop to store frequency of // the characters in a Map for(int i = 0; i < n; i++) if (mp.containsKey(s[i])) { mp.put(s[i], mp.get(s[i]) + 1); } else { mp.put(s[i], 1); } // To store final result int ans = 0; // Traversal of String for(int i = 0; i < n; i++) { // Store answer for every // iteration int cnt = 0; if (mp.containsKey(s[i])) { mp.put(s[i], mp.get(s[i]) - 1); // Map traversal for(Map.Entry<Character, Integer> value : mp.entrySet()) { // Compare current char if (value.getKey() == s[i]) { continue; } else { cnt += value.getValue(); } } ans += cnt; } } // Print the final count System.out.print(ans); } // Driver Code public static void main(String[] args) { // Given String String S = "abcab"; // Length of the String int N = 5; // Function call countSubString(S.toCharArray(), N); } } // This code is contributed by Amit Katiyar
Python3
# Python3 program for the above approach # Function to count the substrings # having different first & last character def countSubstring(s, n): # Stores frequency of each char m = {} # Loop to store frequency of # the characters in a Map for i in range(n): if s[i] in m: m[s[i]] += 1 else: m[s[i]] = 1 # To store final result ans = 0 # Traversal of string for i in range(n): # Store answer for every # iteration cnt = 0 if s[i] in m: m[s[i]] -= 1 else: m[s[i]] = -1 # Map traversal for value in m: # Compare current char if (value == s[i]): continue else: cnt += m[value] ans += cnt # Print the final count print(ans) # Driver code # Given string S = "abcab" # Length of the string N = 5 # Function Call countSubstring(S, N) # This code is contributed by divyeshrabadiya07
C#
// C# program for the above approach using System; using System.Collections.Generic; class GFG{ // Function to count the subStrings // having different first & last character static void countSubString(char []s, int n) { // Stores frequency of each char Dictionary<char, int> mp = new Dictionary<char, int>(); // Loop to store frequency of // the characters in a Map for(int i = 0; i < n; i++) if (mp.ContainsKey(s[i])) { mp[s[i]] = mp[s[i]] + 1; } else { mp.Add(s[i], 1); } // To store readonly result int ans = 0; // Traversal of String for(int i = 0; i < n; i++) { // Store answer for every // iteration int cnt = 0; if (mp.ContainsKey(s[i])) { mp[s[i]] = mp[s[i]] - 1; // Map traversal foreach(KeyValuePair<char, int> value in mp) { // Compare current char if (value.Key == s[i]) { continue; } else { cnt += value.Value; } } ans += cnt; } } // Print the readonly count Console.Write(ans); } // Driver Code public static void Main(String[] args) { // Given String String S = "abcab"; // Length of the String int N = 5; // Function call countSubString(S.ToCharArray(), N); } } // This code is contributed by Amit Katiyar
Javascript
<script> // Javascript program for the above approach // Function to count the substrings // having different first & last character function countSubstring(s, n) { // Stores frequency of each char var m = new Map(); // Loop to store frequency of // the characters in a Map for (var i = 0; i < n; i++) { if(m.has(s[i])) m.set(s[i], m.get(s[i])+1) else m.set(s[i], 1) } // To store final result var ans = 0; // Traversal of string for (var i = 0; i < n; i++) { // Store answer for every // iteration var cnt = 0; if(m.has(s[i])) m.set(s[i], m.get(s[i])-1) // Map traversal m.forEach((value, key) => { // Compare current char if (key != s[i]) { cnt += value; } }); ans += cnt; } // Print the final count document.write( ans); } // Driver Code // Given string var S = "abcab"; // Length of the string var N = 5; // Function Call countSubstring(S, N); // This code is contributed by itsok. </script>
8
Complejidad temporal: O(N*26)
Espacio auxiliar: O(N)
Publicación traducida automáticamente
Artículo escrito por ankitkumar774 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA