ホームページ  >  記事  >  Java  >  繰り返し文字を含まない最長の部分文字列

繰り返し文字を含まない最長の部分文字列

Mary-Kate Olsen
Mary-Kate Olsenオリジナル
2024-09-24 06:21:48613ブラウズ

Longest substring without repeating characters

問題

ブルート フォース アプローチでは、指定された文字列の可能なすべての部分文字列を作成し、繰り返し文字を含まない最も長い部分文字列を見つけます。これは TC:O(n^2)

につながります。

最適なアプローチ:
TC : O(n)
SC : O(256)、サイズ 256 の int[] を使用するため

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;
    }
}

以上が繰り返し文字を含まない最長の部分文字列の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。