题目:
要求给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
代码:
class Solution {
public int lengthOfLongestSubstring(String s) {
// 记录字符上一次出现的位置
int[] last = new int[128];
for(int i = 0; i < 128; i++) {
last[i] = -1;
}
int n = s.length();
//字符长度
int res = 0;
int start = 0; // 窗口开始位置
for(int i = 0; i < n; i++) {
//index为获取s的asic值
int index = s.charAt(i);
//未遇到相同字符则start不变,遇到则截断相同字符前一个字符
start = Math.max(start, last[index] + 1);
//i-start+1为当前字符到start的长度
res = Math.max(res, i - start + 1);
//记录上一次出现该字符的下标
last[index] = i;
}
return res;
}
}
分析:
1)变量分析:
index:获取字符串中字符的ASCII值
last[]:last[index]用于记录index对饮字符的上一次出现的下标索引,初始为-1
res:最长子串长度,初始为0
start:子串的开始位置
2)核心代码分析:
//用于获取字符的ASCII值
int index = s.charAt(i);
/*
截取计算子串的起始位置,初始为0。
遇到重复的字符会调整截取位置,调整结果为该重复字符的上一次出现位置的后一位
例如:a b c d b d
遍历到 a b c d 时last[index] = -1 ,start不变,遍历到第二个b时b的last[index] = 1,
那么start=2
*/
start = Math.max(start, last[index] + 1);
//i-start+1为当前字符到start的长度,若i-start+1更大则更新res
res = Math.max(res, i - start + 1);