最长不含重复字符的子字符串

84 阅读1分钟

最长不含重复字符的子字符串

请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。

假设字符串中只包含从’a’到’z’的字符。

样例
输入:"abcabc"
输出:3

遍历

时间复杂度O(n)

class Solution {
    public int longestSubstringWithoutDuplication(String s) {
        if(s == null || s.length() == 0){
            return 0;
        }
        int max = 0;
        int cur = 0;
        int[] pos = new int[26];
        for(int i = 0;i < 26;i++){
            pos[i] = -1;
        }
        for(int i = 0;i < s.length();i++){
            int tmp = pos[(s.charAt(i) - 'a')];
            if(tmp < 0 ||  (i - tmp) > cur){
                cur++;
            }else{
                if(cur > max){
                    max = cur;
                }
                cur = i - tmp;
            }
            pos[(s.charAt(i) - 'a')] = i;
        }
        if(cur > max){
            max = cur;
        }
        return max;
    }
}