给定一个字符串,查找最长子字符串的长度,不重复字符。
- 输入一串字符:比如给出:
"abaabcdd"
,最长子字符串为:"abcd"
,那么程序输出结果为 4 - 又或者给出:
"bbabcdedff"
,最长子字符串为:"abcde"
,输出结果为 5
/**
* Created by KingsLanding on 2022/9/6 22:50
*/
public class demo05 {
public int lengthOfLongestSubstring(String str) {
int n = str.length();
Set set = new HashSet();
int ans = 0, i = 0, j = 0;
while (i < n && j < n) {
//判断该元素是否存在
if (!set.contains(str.charAt(j))){
//不存在则添加
set.add(str.charAt(j));
j+=1;
//内部的ans会保存当前为止最大的数值,除非j-i大于当前的ans,否则不会改变
ans = Math.max(ans, j - i);
}
else {
//遇见相同的那就删除,主要是为了推进 i
set.remove(str.charAt(i));
i+=1;
}
}
return ans;
}
@Test
public void test(){
int test = lengthOfLongestSubstring("bbabcdedff");
System.out.println(test);//5
}
}