import java.util.*;
//维护一个hashmap 记录上次字符出现的位置。和一个pre,记录上个位置的最长无重复字串
//从左向右逐一更新pre和hashmap的状态
public class DistinctSubstring {
public int longestSubstring(String A, int n) {
int max = 1;
int pre = 0;
HashMap<Character , Integer> hashmap = new HashMap<>();
for(int i=0; i<n; i++){
char c = A.charAt(i);
if(!hashmap.containsKey(c)){
pre++;
}else{
pre = min(++pre, i-hashmap.get(c));
}
hashmap.put(c, i);
if(pre > max){
max = pre;
}
}
return max;
}
public int min(int i, int j){
if(i>j) return j;
else return i;
}
}
连续最长不重复字串其扩展
最新推荐文章于 2024-11-10 10:02:01 发布