Dada una string str , encuentre la longitud de la substring más larga sin repetir caracteres.
Ejemplo:
Para “ABDEFGABEF”, las substrings más largas son “BDEFGA” y “DEFGAB”, con una longitud de 6.
Para «BBBB», la substring más larga es «B», con una longitud de 1.
Para «GEEKSFORGEEKS», hay dos substrings más largas que se muestran en los diagramas a continuación, con una longitud de 7
Método 1 (Simple: O (n 3 )) : Podemos considerar todas las substrings una por una y verificar para cada substring si contiene todos los caracteres únicos o no. Habrá n*(n+1)/2 substrings. Si una substring contiene todos los caracteres únicos o no, se puede verificar en tiempo lineal escaneándola de izquierda a derecha y manteniendo un mapa de los caracteres visitados.
C++
// C++ program to find the length of the longest substring // without repeating characters #include <bits/stdc++.h> using namespace std; // This function returns true if all characters in str[i..j] // are distinct, otherwise returns false bool areDistinct(string str, int i, int j) { // Note : Default values in visited are false vector<bool> visited(26); for (int k = i; k <= j; k++) { if (visited[str[k] - 'a'] == true) return false; visited[str[k] - 'a'] = true; } return true; } // Returns length of the longest substring // with all distinct characters. int longestUniqueSubsttr(string str) { int n = str.size(); int res = 0; // result for (int i = 0; i < n; i++) for (int j = i; j < n; j++) if (areDistinct(str, i, j)) res = max(res, j - i + 1); return res; } // Driver code int main() { string str = "geeksforgeeks"; cout << "The input string is " << str << endl; int len = longestUniqueSubsttr(str); cout << "The length of the longest non-repeating " "character substring is " << len; return 0; } // This code is contributed by Sania Kumari Gupta (kriSania804)
C
// C program to find the length of the longest substring // without repeating characters #include <stdbool.h> #include <stdio.h> #include <string.h> // Find maximum between two numbers. int max(int num1, int num2) { return (num1 > num2) ? num1 : num2; } // This function returns true if all characters in str[i..j] // are distinct, otherwise returns false bool areDistinct(char str[], int i, int j) { // Note : Default values in visited are false bool visited[26]; for(int i=0;i<26;i++) visited[i]=0; for (int k = i; k <= j; k++) { if (visited[str[k] - 'a'] == true) return false; visited[str[k] - 'a'] = true; } return true; } // Returns length of the longest substring // with all distinct characters. int longestUniqueSubsttr(char str[]) { int n = strlen(str); int res = 0; // result for (int i = 0; i < n; i++) for (int j = i; j < n; j++) if (areDistinct(str, i, j)) res = max(res, j - i + 1); return res; } // Driver code int main() { char str[] = "geeksforgeeks"; printf("The input string is %s \n", str); int len = longestUniqueSubsttr(str); printf("The length of the longest non-repeating " "character substring is %d", len); return 0; } // This code is contributed by Sania Kumari Gupta (kriSania804)
Java
// Java program to find the length of the // longest substring without repeating // characters import java.io.*; import java.util.*; class GFG{ // This function returns true if all characters in // str[i..j] are distinct, otherwise returns false public static Boolean areDistinct(String str, int i, int j) { // Note : Default values in visited are false boolean[] visited = new boolean[26]; for(int k = i; k <= j; k++) { if (visited[str.charAt(k) - 'a'] == true) return false; visited[str.charAt(k) - 'a'] = true; } return true; } // Returns length of the longest substring // with all distinct characters. public static int longestUniqueSubsttr(String str) { int n = str.length(); // Result int res = 0; for(int i = 0; i < n; i++) for(int j = i; j < n; j++) if (areDistinct(str, i, j)) res = Math.max(res, j - i + 1); return res; } // Driver code public static void main(String[] args) { String str = "geeksforgeeks"; System.out.println("The input string is " + str); int len = longestUniqueSubsttr(str); System.out.println("The length of the longest " + "non-repeating character " + "substring is " + len); } } // This code is contributed by akhilsaini
Python3
# Python3 program to find the length # of the longest substring without # repeating characters # This function returns true if all # characters in str[i..j] are # distinct, otherwise returns false def areDistinct(str, i, j): # Note : Default values in visited are false visited = [0] * (26) for k in range(i, j + 1): if (visited[ord(str[k]) - ord('a')] == True): return False visited[ord(str[k]) - ord('a')] = True return True # Returns length of the longest substring # with all distinct characters. def longestUniqueSubsttr(str): n = len(str) # Result res = 0 for i in range(n): for j in range(i, n): if (areDistinct(str, i, j)): res = max(res, j - i + 1) return res # Driver code if __name__ == '__main__': str = "geeksforgeeks" print("The input is ", str) len = longestUniqueSubsttr(str) print("The length of the longest " "non-repeating character substring is ", len) # This code is contributed by mohit kumar 29
C#
// C# program to find the length of the // longest substring without repeating // characters using System; class GFG{ // This function returns true if all characters in // str[i..j] are distinct, otherwise returns false public static bool areDistinct(string str, int i, int j) { // Note : Default values in visited are false bool[] visited = new bool[26]; for(int k = i; k <= j; k++) { if (visited[str[k] - 'a'] == true) return false; visited[str[k] - 'a'] = true; } return true; } // Returns length of the longest substring // with all distinct characters. public static int longestUniqueSubsttr(string str) { int n = str.Length; // Result int res = 0; for(int i = 0; i < n; i++) for(int j = i; j < n; j++) if (areDistinct(str, i, j)) res = Math.Max(res, j - i + 1); return res; } // Driver code public static void Main() { string str = "geeksforgeeks"; Console.WriteLine("The input string is " + str); int len = longestUniqueSubsttr(str); Console.WriteLine("The length of the longest " + "non-repeating character " + "substring is " + len); } } // This code is contributed by sanjoy_62
Javascript
<script> // JavaScript program to find the length of the // longest substring without repeating // characters // This function returns true if all characters in // str[i..j] are distinct, otherwise returns false function areDistinct(str, i, j) { // Note : Default values in visited are false var visited = new [26]; for(var k = i; k <= j; k++) { if (visited[str.charAt(k) - 'a'] == true) return false; visited[str.charAt(k) - 'a'] = true; } return true; } // Returns length of the longest substring // with all distinct characters. function longestUniqueSubsttr(str) { var n = str.length(); // Result var res = 0; for(var i = 0; i < n; i++) for(var j = i; j < n; j++) if (areDistinct(str, i, j)) res = Math.max(res, j - i + 1); return res; } // Driver code var str = "geeksforgeeks"; document.write("The input string is " + str); var len = longestUniqueSubsttr(str); document.write("The length of the longest " + "non-repeating character " + "substring is " + len); // This code is contributed by shivanisinghss2110. </script>
The input string is geeksforgeeks The length of the longest non-repeating character substring is 7
Complejidad de tiempo: O (n ^ 3) ya que estamos procesando n ^ 2 substrings con una longitud máxima n .
Espacio Auxiliar: O(1)
Método 2 (Mejor : O(n 2 )) La idea es usar ventana deslizante . Siempre que vemos repetición, eliminamos la ocurrencia anterior y deslizamos la ventana.
C++
// C++ program to find the length of the longest substring // without repeating characters #include <bits/stdc++.h> using namespace std; int longestUniqueSubsttr(string str) { int n = str.size(); int res = 0; // result for (int i = 0; i < n; i++) { // Note : Default values in visited are false vector<bool> visited(256); for (int j = i; j < n; j++) { // If current character is visited // Break the loop if (visited[str[j]] == true) break; // Else update the result if // this window is larger, and mark // current character as visited. else { res = max(res, j - i + 1); visited[str[j]] = true; } } // Remove the first character of previous // window visited[str[i]] = false; } return res; } // Driver code int main() { string str = "geeksforgeeks"; cout << "The input string is " << str << endl; int len = longestUniqueSubsttr(str); cout << "The length of the longest non-repeating " "character substring is " << len; return 0; }
Java
// Java program to find the length of the // longest substring without repeating // characters import java.io.*; import java.util.*; class GFG{ public static int longestUniqueSubsttr(String str) { int n = str.length(); // Result int res = 0; for(int i = 0; i < n; i++) { // Note : Default values in visited are false boolean[] visited = new boolean[256]; for(int j = i; j < n; j++) { // If current character is visited // Break the loop if (visited[str.charAt(j)] == true) break; // Else update the result if // this window is larger, and mark // current character as visited. else { res = Math.max(res, j - i + 1); visited[str.charAt(j)] = true; } } // Remove the first character of previous // window visited[str.charAt(i)] = false; } return res; } // Driver code public static void main(String[] args) { String str = "geeksforgeeks"; System.out.println("The input string is " + str); int len = longestUniqueSubsttr(str); System.out.println("The length of the longest " + "non-repeating character " + "substring is " + len); } } // This code is contributed by akhilsaini
Python3
# Python3 program to find the # length of the longest substring # without repeating characters def longestUniqueSubsttr(str): n = len(str) # Result res = 0 for i in range(n): # Note : Default values in # visited are false visited = [0] * 256 for j in range(i, n): # If current character is visited # Break the loop if (visited[ord(str[j])] == True): break # Else update the result if # this window is larger, and mark # current character as visited. else: res = max(res, j - i + 1) visited[ord(str[j])] = True # Remove the first character of previous # window visited[ord(str[i])] = False return res # Driver code str = "geeksforgeeks" print("The input is ", str) len = longestUniqueSubsttr(str) print("The length of the longest " "non-repeating character substring is ", len) # This code is contributed by sanjoy_62
C#
// C# program to find the length of the // longest substring without repeating // characters using System; class GFG{ static int longestUniqueSubsttr(string str) { int n = str.Length; // Result int res = 0; for(int i = 0; i < n; i++) { // Note : Default values in visited are false bool[] visited = new bool[256]; // visited = visited.Select(i => false).ToArray(); for(int j = i; j < n; j++) { // If current character is visited // Break the loop if (visited[str[j]] == true) break; // Else update the result if // this window is larger, and mark // current character as visited. else { res = Math.Max(res, j - i + 1); visited[str[j]] = true; } } // Remove the first character of previous // window visited[str[i]] = false; } return res; } // Driver code static void Main() { string str = "geeksforgeeks"; Console.WriteLine("The input string is " + str); int len = longestUniqueSubsttr(str); Console.WriteLine("The length of the longest " + "non-repeating character " + "substring is " + len ); } } // This code is contributed by divyeshrabadiya07
Javascript
<script> // JavaScript program to find the length of the // longest substring without repeating // characters function longestUniqueSubsttr(str) { var n = str.length(); // Result var res = 0; for(var i = 0; i < n; i++) { // Note : Default values in visited are false var visited = new Array(256); for(var j = i; j < n; j++) { // If current character is visited // Break the loop if (visited[str.charCodeAt(j)] == true) break; // Else update the result if // this window is larger, and mark // current character as visited. else { res = Math.max(res, j - i + 1); visited[str.charCodeAt(j)] = true; } } } return res; } // Driver code var str = "geeksforgeeks"; document.write("The input string is " + str); var len = longestUniqueSubsttr(str); document.write("The length of the longest " + "non-repeating character " + "substring is " + len); // This code is contributed by shivanisinghss2110 // This code is edited by ziyak9803 </script>
The input string is geeksforgeeks The length of the longest non-repeating character substring is 7
Complejidad de tiempo: O (n ^ 2) ya que estamos atravesando cada ventana para eliminar todas las repeticiones.
Espacio Auxiliar: O(1)
Método 3 (Tiempo lineal) : Usando esta solución, el problema se puede resolver en tiempo lineal usando la técnica de deslizamiento de ventana. Cada vez que vemos repetición, quitamos la ventana hasta la string repetida.
Java
import java.io.*; class GFG { public static int longestUniqueSubsttr(String str) { String test = ""; // Result int maxLength = -1; // Return zero if string is empty if (str.isEmpty()) { return 0; } // Return one if string length is one else if (str.length() == 1) { return 1; } for (char c : str.toCharArray()) { String current = String.valueOf(c); // If string already contains the character // Then substring after repeating character if (test.contains(current)) { test = test.substring(test.indexOf(current) + 1); } test = test + String.valueOf(c); maxLength = Math.max(test.length(), maxLength); } return maxLength; } // Driver code public static void main(String[] args) { String str = "geeksforgeeks"; System.out.println("The input string is " + str); int len = longestUniqueSubsttr(str); System.out.println("The length of the longest " + "non-repeating character " + "substring is " + len); } } // This code is contributed by Alex Bennet
The input string is geeksforgeeks The length of the longest non-repeating character substring is 7
Complejidad temporal: O(n) ya que deslizamos la ventana cada vez que vemos repeticiones.
Espacio Auxiliar: O(1)
Método 4 (Tiempo lineal) : Hablemos ahora de la solución de tiempo lineal. Esta solución utiliza espacio adicional para almacenar los últimos índices de caracteres ya visitados. La idea es escanear la string de izquierda a derecha, realizar un seguimiento de la substring de caracteres no repetidos de longitud máxima vista hasta ahora en res . Cuando recorremos la string, para saber la longitud de la ventana actual necesitamos dos índices.
1) Índice final ( j ): Consideramos el índice actual como índice final.
2) Índice inicial ( i ): Es igual que la ventana anterior si el carácter actual no estaba presente en la ventana anterior. Para verificar si el carácter actual estaba presente en la ventana anterior o no, almacenamos el último índice de cada carácter en una array lasIndex[]. Si lastIndex[str[j]] + 1 es más que el inicio anterior, entonces actualizamos el índice de inicio i. De lo contrario, mantenemos el mismo i.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program to find the length of the longest substring // without repeating characters #include <bits/stdc++.h> using namespace std; #define NO_OF_CHARS 256 int longestUniqueSubsttr(string str) { int n = str.size(); int res = 0; // result // last index of all characters is initialized // as -1 vector<int> lastIndex(NO_OF_CHARS, -1); // Initialize start of current window int i = 0; // Move end of current window for (int j = 0; j < n; j++) { // Find the last index of str[j] // Update i (starting index of current window) // as maximum of current value of i and last // index plus 1 i = max(i, lastIndex[str[j]] + 1); // Update result if we get a larger window res = max(res, j - i + 1); // Update last index of j. lastIndex[str[j]] = j; } return res; } // Driver code int main() { string str = "geeksforgeeks"; cout << "The input string is " << str << endl; int len = longestUniqueSubsttr(str); cout << "The length of the longest non-repeating " "character substring is " << len; return 0; }
Java
// Java program to find the length of the longest substring // without repeating characters import java.util.*; public class GFG { static final int NO_OF_CHARS = 256; static int longestUniqueSubsttr(String str) { int n = str.length(); int res = 0; // result // last index of all characters is initialized // as -1 int [] lastIndex = new int[NO_OF_CHARS]; Arrays.fill(lastIndex, -1); // Initialize start of current window int i = 0; // Move end of current window for (int j = 0; j < n; j++) { // Find the last index of str[j] // Update i (starting index of current window) // as maximum of current value of i and last // index plus 1 i = Math.max(i, lastIndex[str.charAt(j)] + 1); // Update result if we get a larger window res = Math.max(res, j - i + 1); // Update last index of j. lastIndex[str.charAt(j)] = j; } return res; } /* Driver program to test above function */ public static void main(String[] args) { String str = "geeksforgeeks"; System.out.println("The input string is " + str); int len = longestUniqueSubsttr(str); System.out.println("The length of " + "the longest non repeating character is " + len); } } // This code is contributed by Sumit Ghosh
Python3
# Python3 program to find the length # of the longest substring # without repeating characters def longestUniqueSubsttr(string): # last index of every character last_idx = {} max_len = 0 # starting index of current # window to calculate max_len start_idx = 0 for i in range(0, len(string)): # Find the last index of str[i] # Update start_idx (starting index of current window) # as maximum of current value of start_idx and last # index plus 1 if string[i] in last_idx: start_idx = max(start_idx, last_idx[string[i]] + 1) # Update result if we get a larger window max_len = max(max_len, i-start_idx + 1) # Update last index of current char. last_idx[string[i]] = i return max_len # Driver program to test the above function string = "geeksforgeeks" print("The input string is " + string) length = longestUniqueSubsttr(string) print("The length of the longest non-repeating character" + " substring is " + str(length))
C#
// C# program to find the length of the longest substring // without repeating characters using System; public class GFG { static int NO_OF_CHARS = 256; static int longestUniqueSubsttr(string str) { int n = str.Length; int res = 0; // result // last index of all characters is initialized // as -1 int [] lastIndex = new int[NO_OF_CHARS]; Array.Fill(lastIndex, -1); // Initialize start of current window int i = 0; // Move end of current window for (int j = 0; j < n; j++) { // Find the last index of str[j] // Update i (starting index of current window) // as maximum of current value of i and last // index plus 1 i = Math.Max(i, lastIndex[str[j]] + 1); // Update result if we get a larger window res = Math.Max(res, j - i + 1); // Update last index of j. lastIndex[str[j]] = j; } return res; } /* Driver program to test above function */ static public void Main () { string str = "geeksforgeeks"; Console.WriteLine("The input string is " + str); int len = longestUniqueSubsttr(str); Console.WriteLine("The length of "+ "the longest non repeating character is " + len); } } // This code is contributed by avanitrachhadiya2155
Javascript
<script> // JavaScript program to find the length of the longest substring // without repeating characters var NO_OF_CHARS = 256; function longestUniqueSubsttr(str) { var n = str.length(); var res = 0; // result // last index of all characters is initialized // as -1 var lastIndex = new [NO_OF_CHARS]; Arrays.fill(lastIndex, -1); // Initialize start of current window var i = 0; // Move end of current window for (var j = 0; j < n; j++) { // Find the last index of str[j] // Update i (starting index of current window) // as maximum of current value of i and last // index plus 1 i = Math.max(i, lastIndex[str.charAt(j)] + 1); // Update result if we get a larger window res = Math.max(res, j - i + 1); // Update last index of j. lastIndex[str.charAt(j)] = j; } return res; } /* Driver program to test above function */ var str = "geeksforgeeks"; document.write("The input string is " + str); var len = longestUniqueSubsttr(str); document.write("The length of the longest non repeating character is " + len); // This code is contributed by shivanisinghss2110 </script>
The input string is geeksforgeeks The length of the longest non-repeating character substring is 7
Complejidad de tiempo: O(n + d) donde n es la longitud de la string de entrada y d es el número de caracteres en el alfabeto de la string de entrada. Por ejemplo, si la string consta de caracteres ingleses en minúsculas, el valor de d es 26.
Espacio auxiliar: O(d)
Implementación alternativa:
C++
#include <bits/stdc++.h> using namespace std; int longestUniqueSubsttr(string s) { // Creating a map to store the last positions // of occurrence map<char, int> seen ; int maximum_length = 0; // Starting the initial point of window to index 0 int start = 0; for(int end = 0; end < s.length(); end++) { // Checking if we have already seen the element or // not if (seen.find(s[end]) != seen.end()) { // If we have seen the number, move the start // pointer to position after the last occurrence start = max(start, seen[s[end]] + 1); } // Updating the last seen value of the character seen[s[end]] = end; maximum_length = max(maximum_length, end - start + 1); } return maximum_length; } // Driver code int main() { string s = "geeksforgeeks"; cout << "The input String is " << s << endl; int length = longestUniqueSubsttr(s); cout<<"The length of the longest non-repeating character " <<"substring is " << length; } // This code is contributed by ukasp
Java
import java.util.*; class GFG { static int longestUniqueSubsttr(String s) { // Creating a set to store the last positions of occurrence HashMap<Character, Integer> seen = new HashMap<>(); int maximum_length = 0; // starting the initial point of window to index 0 int start = 0; for(int end = 0; end < s.length(); end++) { // Checking if we have already seen the element or not if(seen.containsKey(s.charAt(end))) { // If we have seen the number, move the start pointer // to position after the last occurrence start = Math.max(start, seen.get(s.charAt(end)) + 1); } // Updating the last seen value of the character seen.put(s.charAt(end), end); maximum_length = Math.max(maximum_length, end-start + 1); } return maximum_length; } // Driver code public static void main(String []args) { String s = "geeksforgeeks"; System.out.println("The input String is " + s); int length = longestUniqueSubsttr(s); System.out.println("The length of the longest non-repeating character substring is " + length); } } // This code is contributed by rutvik_56.
Python3
# Here, we are planning to implement a simple sliding window methodology def longestUniqueSubsttr(string): # Creating a set to store the last positions of occurrence seen = {} maximum_length = 0 # starting the initial point of window to index 0 start = 0 for end in range(len(string)): # Checking if we have already seen the element or not if string[end] in seen: # If we have seen the number, move the start pointer # to position after the last occurrence start = max(start, seen[string[end]] + 1) # Updating the last seen value of the character seen[string[end]] = end maximum_length = max(maximum_length, end-start + 1) return maximum_length # Driver Code string = "geeksforgeeks" print("The input string is", string) length = longestUniqueSubsttr(string) print("The length of the longest non-repeating character substring is", length)
C#
using System; using System.Collections.Generic; class GFG { static int longestUniqueSubsttr(string s) { // Creating a set to store the last positions of occurrence Dictionary<char, int> seen = new Dictionary<char, int>(); int maximum_length = 0; // starting the initial point of window to index 0 int start = 0; for(int end = 0; end < s.Length; end++) { // Checking if we have already seen the element or not if(seen.ContainsKey(s[end])) { // If we have seen the number, move the start pointer // to position after the last occurrence start = Math.Max(start, seen[s[end]] + 1); } // Updating the last seen value of the character seen[s[end]] = end; maximum_length = Math.Max(maximum_length, end-start + 1); } return maximum_length; } // Driver code static void Main() { string s = "geeksforgeeks"; Console.WriteLine("The input string is " + s); int length = longestUniqueSubsttr(s); Console.WriteLine("The length of the longest non-repeating character substring is " + length); } } // This code is contributed by divyesh072019.
Javascript
<script> function longestUniqueSubsttr(s) { // Creating a set to store the last positions // of occurrence let seen = new Map(); let maximum_length = 0; // Starting the initial point of window to index 0 let start = 0; for(let end = 0; end < s.length; end++) { // Checking if we have already seen the element or // not if (seen.has(s[end])) { // If we have seen the number, move the start // pointer to position after the last occurrence start = Math.max(start, seen.get(s[end]) + 1); } // Updating the last seen value of the character seen.set(s[end],end) maximum_length = Math.max(maximum_length, end - start + 1); } return maximum_length; } // Driver code let s = "geeksforgeeks" document.write(`The input String is ${s}`) let length = longestUniqueSubsttr(s); document.write(`The length of the longest non-repeating character substring is ${length}`) // This code is contributed by shinjanpatra </script>
The input String is geeksforgeeks The length of the longest non-repeating character substring is 7
Complejidad temporal: O(n + d)donde n es la longitud de la string de entrada y d es el número de caracteres en el alfabeto de la string de entrada. Por ejemplo, si la string consta de caracteres ingleses en minúsculas, el valor de d es 26.
Espacio auxiliar: O(d)
Como ejercicio, intente la versión modificada del problema anterior donde también necesita imprimir la longitud máxima de NRCS (el programa anterior solo imprime la longitud).
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA