自己写的:
public static int lengthOfLongestSubstring(String s) {
int max = 0; //如果字符串长度为0 直接返回长度0
char[] c = s.toCharArray();
Set<Character> set = new HashSet<>(); //利用Set中不能含有相同元素的性质
for (int i = 0; i < c.length; i++) { //遍历字符串中的每一个字符
if (!set.add(c[i])) { //每次都会判断set中是否已经有了该字符,没有 就添加进去,有就计算set中字符的个数
max = Math.max(max, set.size()); //与最大长度比较 取大的赋给最大长度
set.clear(); //清空set
for (int j = i; j > 0; j--) { //从该重复元素下标往前 遍历
// 将字符重新存入set中,直至遇到与自己重复的为止 相当于开始一个新的长度计数,再继续遍历字符串的下一个元素
if (!set.add(c[j])) break;
}
}
//这个主要针对字符串中所有元素都不重复的现象
max = Math.max(max, set.size());
}
return max;
}
discuss里面的解法:
public static int lengthOfLongestSubstring1(String s) {
//主要利用队列先进先出的性质 快速解决了上述方法中第二个for循环所解决的问题
Queue<Character> queue = new LinkedList<>();
int max = 0;
//遍历字符串中的字符元素
for (char c : s.toCharArray()) {
//如果遇到重复元素,从queue中第一个元素开始移除 直至不含有重复元素
while (queue.contains(c)) {
queue.remove();
}
//不含有重复元素 向queue中添加字符
queue.add(c);
max = Math.max(max, queue.size()); //每次比较长度
}
return max;
}
3. Longest Substring Without Repeating Characters解法
最新推荐文章于 2025-07-16 15:57:19 发布