Dada una string str , la tarea es contar todas las posibles substrings de la string dada que son prefijos de la misma string.
Ejemplos:
Entrada: str = «ababc»
Salida: 7
Todas las substrings posibles son «a», «ab», «aba», «abab», «ababc», «a» y «ab»Entrada: str = «abdabc»
Salida: 8
Enfoque: recorra la string carácter por carácter, si el carácter actual es igual al primer carácter de la string, cuente todas las substrings posibles a partir de aquí que también son los prefijos de str y agréguelas a count . Después de recorrer la string completa, imprima el conteo .
A continuación se muestra la implementación del enfoque anterior:
C++14
// C++ implementation of the approach #include <iostream> #include <string> using namespace std; // Function to return the // count of sub-strings starting // from startIndex that are // also the prefixes of str int subStringsStartingHere(string str, int n, int startIndex) { int count = 0, i = 1; while (i <= n) { if (str.substr(0,i) == str.substr(startIndex, i)) { count++; } else break; i++; } return count; } // Function to return the // count of all possible sub-strings // of str that are also the prefixes of str int countSubStrings(string str, int n) { int count = 0; for (int i = 0; i < n; i++) { // If current character is equal to // the starting character of str if (str[i] == str[0]) count += subStringsStartingHere(str, n, i); } return count; } // Driver code int main() { string str = "abcda"; int n = str.length(); // Function Call cout << (countSubStrings(str, n)); } // This code is contributed by harshvijeta0
Java
// Java implementation of the approach public class GFG { // Function to return // the count of sub-strings starting // from startIndex that // are also the prefixes of str public static int subStringsStartingHere( String str, int n, int startIndex) { int count = 0, i = startIndex + 1; while (i <= n) { if (str.startsWith(str.substring( startIndex, i))) { count++; } else break; i++; } return count; } // Function to return the // count of all possible sub-strings // of str that are also the prefixes of str public static int countSubStrings(String str, int n) { int count = 0; for (int i = 0; i < n; i++) { // If current character is equal to // the starting character of str if (str.charAt(i) == str.charAt(0)) count += subStringsStartingHere(str, n, i); } return count; } // Driver code public static void main(String[] args) { String str = "ababc"; int n = str.length(); System.out.println(countSubStrings(str, n)); } }
Python3
# Python3 implementation of the approach # Function to return the # count of sub-strings starting # from startIndex that are # also the prefixes of string def subStringsStartingHere(string, n, startIndex): count = 0 i = startIndex + 1 while(i <= n) : if string.startswith( string[startIndex : i]): count += 1 else : break i += 1 return count # Function to return the # count of all possible sub-strings # of string that are also # the prefixes of string def countSubStrings(string, n) : count = 0 for i in range(n) : # If current character is equal to # the starting character of str if string[i] == string[0] : count += subStringsStartingHere( string, n, i) return count # Driver Code if __name__ == "__main__" : string = "ababc" n = len(string) print(countSubStrings(string, n)) # this code is contributed by Ryuga
C#
// C# implementation of the approach using System; class GFG { // Function to return the // count of sub-strings starting // from startIndex that // are also the prefixes of str static int subStringsStartingHere( String str, int n, int startIndex) { int count = 0, i = startIndex + 1; while (i <= n) { if (str.StartsWith(str.Substring( startIndex, i-startIndex))) { count++; } else break; i++; } return count; } // Function to return the // count of all possible sub-strings // of str that are also the prefixes of str static int countSubStrings(String str, int n) { int count = 0; for (int i = 0; i < n; i++) { // If current character is equal to // the starting character of str if (str[i] == str[0]) count += subStringsStartingHere( str, n, i); } return count; } // Driver code static public void Main(String []args) { String str = "ababc"; int n = str.Length; Console.WriteLine(countSubStrings(str, n)); } } //contributed by Arnab Kundu
Javascript
<script> // Javascript implementation of the approach // Function to return the // count of sub-strings starting // from startIndex that are // also the prefixes of str function subStringsStartingHere(str, n, startIndex) { var count = 0, i = startIndex + 1; while (i <= n) { if (str.startsWith( str.substring(startIndex, i))) { count++; } else break; i++; } return count; } // Function to return the count of all // possible sub-strings of str that are // also the prefixes of str function countSubStrings(str, n) { var count = 0; for(var i = 0; i < n; i++) { // If current character is equal to // the starting character of str if (str[i] == str[0]) count += subStringsStartingHere(str, n, i); } return count; } // Driver code var str = "abcda"; var n = str.length; // Function Call document.write(countSubStrings(str, n)); // This code is contributed by rutvik_56 </script>
6
Complejidad de tiempo: O(N^2)
Espacio auxiliar: O(1)
Enfoque eficiente:
Prerrequisito: Algoritmo Z
Enfoque: Calcule la array z de la string de modo que z[i] almacene la longitud de la substring más larga a partir de i, que también es un prefijo de la string s. Luego, para contar todas las substrings posibles de la string que son prefijos de la misma string, solo necesitamos sumar todos los valores de la array z, ya que el número total de substrings coincidentes sería igual a la longitud de la substring más larga.
Implementación del enfoque anterior: –
C++
#include <bits/stdc++.h> using namespace std; // returns an array z such that z[i] // stores length of the longest substring starting // from i which is also a prefix of string s vector<int> z_function(string s) { int n = (int)s.length(); vector<int> z(n); // consider a window [l,r] // which matches with prefix of s int l = 0, r = 0; z[0] = n; for (int i = 1; i < n; ++i) { // when i<=r, we make use of already computed z // value for some smaller index if (i <= r) z[i] = min(r - i + 1, z[i - l]); // if i>r nothing matches so we will calculate // z[i] using naive way. while (i + z[i] < n && s[z[i]] == s[i + z[i]]) ++z[i]; // update window size if (i + z[i] - 1 > r) l = i, r = i + z[i] - 1; } return z; } int main() { string s = "abcda"; int n = s.length(); vector<int> z = z_function(s); // stores the count of // Sub-strings of a string that // are prefix of the same string int count = 0; for (auto x : z) count += x; cout << count << '\n'; return 0; }
Python3
# returns an array z such that z[i] # stores length of the longest substring starting # from i which is also a prefix of s def z_function(s): n = len(s) z=[0]*n # consider a window [l,r] # which matches with prefix of s l = 0; r = 0 z[0] = n for i in range(1, n) : # when i<=r, we make use of already computed z # value for some smaller index if (i <= r): z[i] = min(r - i + 1, z[i - l]) # if i>r nothing matches so we will calculate # z[i] using naive way. while (i + z[i] < n and s[z[i]] == s[i + z[i]]): z[i]+=1 # update window size if (i + z[i] - 1 > r): l = i; r = i + z[i] - 1 return z if __name__ == '__main__': s = "abcda" n = len(s) z = z_function(s) # stores the count of # Sub-strings of a that # are prefix of the same string count = 0 for x in z: count += x print(count)
Javascript
<script> // JavaScript code for the approach // returns an array z such that z[i] // stores length of the longest substring starting // from i which is also a prefix of string s function z_function(s) { let n = s.length; let z = new Array(n).fill(0); // consider a window [l,r] // which matches with prefix of s let l = 0, r = 0; z[0] = n; for (let i = 1; i < n; i++) { // when i<=r, we make use of already computed z // value for some smaller index if (i <= r) z[i] = Math.min(r - i + 1, z[i - l]); // if i>r nothing matches so we will calculate // z[i] using naive way. while (i + z[i] < n && s[z[i]] == s[i + z[i]]) z[i]++; // update window size if (i + z[i] - 1 > r) l = i, r = i + z[i] - 1; } return z; } // driver code let s = "abcda"; let n = s.length; let z = z_function(s); // stores the count of // Sub-strings of a string that // are prefix of the same string let count = 0; for (let x of z) count += x; document.write(count) // This code is contributed by shinjanpatra </script>
6
Complejidad de tiempo: O(n)
Espacio Auxiliar: O(n)
Publicación traducida automáticamente
Artículo escrito por rituraj_jain y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA