Programa Java para encontrar la longitud de la substring más larga sin repetir caracteres

Dada una string str , encuentre la longitud de la substring más larga sin repetir caracteres. 

  • 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

La complejidad de tiempo deseada es O(n) donde n es la longitud de la string.

 

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. La complejidad temporal de esta solución sería O(n^3).

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
Producción

The input string is geeksforgeeks
The length of the longest non-repeating character substring is 7

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.

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
Producción

The input string is geeksforgeeks
The length of the longest non-repeating character substring is 7

Método 3 (Tiempo lineal) : Usando esta solución, el problema se puede resolver en tiempo lineal usando la técnica de deslizamiento de ventanas. 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
Producción

The input string is geeksforgeeks
The length of the longest non-repeating character substring is 7

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:

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
Producción

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: 

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.
Producción

The input String is geeksforgeeks
The length of the longest non-repeating character substring is 7

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).

Consulte el artículo completo sobre Longitud de la substring más larga sin repetir caracteres para obtener más detalles.

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

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *