当前位置: 首页 > 图灵资讯 > 技术篇> 没有重复字符的最长子串

没有重复字符的最长子串

来源:图灵教育
时间:2024-09-29 20:26:11

没有重复字符的最长子串

问题

暴力方法将涉及到创建给定字符串的所有可能的子字符串,并找出没有重复字符的最长子字符串。这将导致 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 means the character has been seen in past>=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;
    }
}
</s.length>

以上是没有重复字符的最长子串的详细内容。请关注图灵教育的其他相关文章!