Maison  >  Article  >  Java  >  Sous-chaîne la plus longue sans caractères répétitifs

Sous-chaîne la plus longue sans caractères répétitifs

Mary-Kate Olsen
Mary-Kate Olsenoriginal
2024-09-24 06:21:48614parcourir

Longest substring without repeating characters

Problème

L'approche par force brute impliquera de créer toutes les sous-chaînes possibles de la chaîne donnée et de découvrir laquelle est la sous-chaîne la plus longue sans le caractère répétitif. Cela mènera à TC:O(n^2)

Approche optimale :
TC : O(n)
SC : O(256), pour utiliser int[] de taille 256

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int hash[] = new int[256];// size of all the ascii characters
        Arrays.fill(hash,-1); // -1 to indicate these indexes don't have any character visited already
        int left =0,right =0;
        int max = 0;
        while(right<s.length()){
            char  c = s.charAt(right);
            if(hash[c]!=-1){// means the character has been seen in the past
                if(hash[c]>=left){// if the index of the character seen in the past is after the left pointer, then left pointer should be updated, to avoid duplicate in the window of substring
                    left  = hash[c] + 1;// has to be 1 index after the index of last seen duplicate character
                }
            }
            max = Integer.max(max, right-left+1);// keep track of mas window substring
            hash[c]  = right;// update the character last seen index in hash
            right++;
        }
        return max;
    }
}

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn