参考博客:
https://blog.csdn.net/weixin_38361153/article/details/88925999
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 面试题48:最长不含重复字符的子字符串
* 题目:青葱字符串中找出一个最长的不包含重复字符的子字符串,计算该最长字符串的长度。
* 假设字符串中只包含'a'~'z'的字符。例如,在字符串"arabcacfr"中,最长的不含重复字符的子字符串是
* "acfr",长度为4。
* @author
* @create 2021-04-19 13:23
*/
public class Solution48 {
public static void main(String[] args) {
String str = "arabcacfr";
System.out.println(longestSubstring(str));
}
/**
* 方法一:
* @param str
* @return
*/
public static int longestSubstringWithoutDuplication(String str) {
if (str == null || str.equals("")){
return 0;
}
//动态规划+重复字符之间的距离
int maxLength = 0;
int curLength = 0;
int[] position = new int[26];//存储每个字符上次出现在字符串中位置的下标
Arrays.fill(position,-1);//初始化为-1,表示该元素对应的字符在字符串中还没有出现过
int n = str.length();
for (int i = 0; i < n; i++) {
int preIndex = position[str.charAt(i) - 'a'];
int distance = i - preIndex;//计算到上次出现的距离
if (preIndex < 0 || distance > curLength){
//没出现过或者距离大于当前最长子串长度,curLength++
curLength++;
}else {
//出现过且距离小于或等于最长子串的长度,
if (curLength > maxLength){
maxLength = curLength;
}
curLength = distance;
}
position[str.charAt(i) - 'a'] = i;//更新该字符上次出现的位置
}
if (curLength > maxLength){
maxLength = curLength;
}
return maxLength;
}
/**
* 方法二:用list
* @param str
* @return
*/
public static int longestSubstring(String str) {
if (str == null || str.equals("")){
return 0;
}
List<Character> list = new ArrayList<>();
list.add(str.charAt(0));
int n = str.length();
int maxLength = 0;
for (int i = 1; i < n; i++) {
char c = str.charAt(i);
if (!list.contains(c)){
list.add(c);
}else {
//找不到就返回-1,是查找当前list中的index,而不是在字符串中的index
int index = list.indexOf(c);
// if (i - index <= list.size()){
//i是字符串中的索引,index是list中的索引,会出现差错
// list = list.subList(index+1,list.size());//左闭右开区间
// }
// 只要出现过,就截取上次出现的后一个位置到尾部元素,保证list中都是没有重复的字符
list = list.subList(index+1,list.size());
list.add(c);
}
if (list.size() > maxLength){
//每一次循环都会记录最大值
maxLength = list.size();
}
}
System.out.println(list);
return maxLength;
}
}