public static int getMaxLengthUnRepeatSubString(String str) {
// 题目中以假设该字符串只包含a-z的字符,无需安全检查
// 储存每一个字符在字符串str中出现的最新位置
int[] words = new int[26];
for (int i = 0; i < words.length; i++) {
words[i] = -1;
}
int max = 0;
int curCharIndexOfWords = 0; // 当前字符对应在words数组中的下标 a-0,b-1...
int start = 0; // 每次计算最长子字符串长度的起点
for (int cur = 0; cur < str.length(); cur++) {
curCharIndexOfWords = str.charAt(cur) - 'a';
if (words[curCharIndexOfWords] == -1) { // 第一次出现
words[curCharIndexOfWords] = cur;
}else {
max = Math.max(max, cur - start);
start = words[curCharIndexOfWords] + 1;
words[curCharIndexOfWords] = cur; // 更新当前字符的最新位置
}
}
return max;
}
最长不含重复字符的子字符串
最新推荐文章于 2024-02-19 20:09:09 发布