import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型
*/
public int lengthOfLongestSubstring (String s) {
if (s == null || s.length() == 0) {
return 0;
}
// 哈希表用来存储s中不重复的字符
HashSet<Character> hashSet = new HashSet<>();
int tempLength = 1;
int maxLength = Integer.MIN_VALUE;
hashSet.add(s.charAt(0));
for (int i = 1; i < s.length(); i++) {
char c = s.charAt(i);
// 如果不重复添加到哈希表,临时长度+1
if (!hashSet.contains(c)) {
hashSet.add(c);
tempLength++;
} else {
// 取最大长度
maxLength = Math.max(maxLength, tempLength);
// 重新被赋值为1
tempLength = 1;
}
}
// 如果全都是不重复的,那么可能没走 else 中的Math.max
maxLength = Math.max(tempLength, maxLength);
return maxLength;
}
}
本题知识点分析:
1.哈希表
2.动态规划
3.数学模拟
4.API函数(Math.max)
本题解题思路分析:
1.哈希表用来存储不重复的字符
2. 如果不重复添加到哈希表,临时长度+1
3.如果出现重复,表明可以更新最大长度
4.for循环遍历完一遍后,再Math.max一次
5.可以用dp规划做,但要两次遍历O(n)的复杂度,所以就没写。
本题使用编程语言: Java
如果你觉得本篇文章对你有帮助的话,可以点个赞支持一下,感谢~

京公网安备 11010502036488号