#小黑代码
class Solution {
public int lengthOfLongestSubstring(String s) {
int start = 0, end = 0; //起止标记
int length = s.length();
int max = 0; //记录字符串长度
Set set = new HashSet<Character>();
while(end<length) {
while(set.contains(s.charAt(end))) { //j依次向后判断如果有重复,则起始位置i加1
set.remove(s.charAt(start));
start++;
}
set.add(s.charAt(end));
if(end-start+1>max) {
max = end-start+1;
}
end++;
}
return max;
}
}
#leetcode代码
public class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length(), ans = 0;
Map<Character, Integer> map = new HashMap<>(); // current index of character
// try to extend the range [i, j]
for (int j = 0, i = 0; j < n; j++) {
if (map.containsKey(s.charAt(j))) { //判断是否在其中,寻找下一个j为结尾的(最靠前的i)的无重复字符串
i = Math.max(map.get(s.charAt(j)), i);
}
ans = Math.max(ans, j - i + 1);
map.put(s.charAt(j), j + 1);
}
return ans;
}
}
3.无重复序列子串
最新推荐文章于 2024-06-29 23:00:55 发布