All Downloads are FREE. Search and download functionalities are using the official Maven repository.

s0003.longest.substring.without.repeating.characters.Solution Maven / Gradle / Ivy

package s0003.longest.substring.without.repeating.characters;

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int lastIndices[] = new int[256];
        for (int i = 0; i < 256; i++) {
            lastIndices[i] = -1;
        }

        int maxLen = 0;
        int curLen = 0;
        int start = 0;
        int bestStart = 0;
        for (int i = 0; i < s.length(); i++) {
            char cur = s.charAt(i);
            if (lastIndices[cur] < start) {
                lastIndices[cur] = i;
                curLen++;
            } else {
                int lastIndex = lastIndices[cur];
                start = lastIndex + 1;
                curLen = i - start + 1;
                lastIndices[cur] = i;
            }

            if (curLen > maxLen) {
                maxLen = curLen;
                bestStart = start;
            }
        }

        return maxLen;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy