网站首页 > 文章精选 正文
来源:力扣(LeetCode)
链接:
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
题目描述
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
题目分析
滑动窗口
思路:两个指针表示字符串中的某个子串(或窗口)的左右边界。左指针向右移动一格,移除一个字符;不断向右移动 右指针。哈希集合,记录每个字符是否出现过,
代码实现
public class LengthOfLongestSubstring_3 {
public static void main(String[] args) {
LengthOfLongestSubstring_3 main = new LengthOfLongestSubstring_3();
int result = main.lengthOfLongestSubstring("abcdee");
System.out.println("result:" + result);
}
public int lengthOfLongestSubstring(String s) {
int result = 0;
int end = 0;
// 哈希集合,记录每个字符是否出现过
Set<Character> occ = new HashSet<Character>();
for (int i = 0; i < s.length(); i++) {
if (i > 0) {
// 左指针向右移动一格,移除一个字符
occ.remove(s.charAt(i - 1));
}
// 不断向右移动 右指针
while (end < s.length() && !occ.contains(s.charAt(end))){
occ.add(s.charAt(end));
end++;
}
int length = end - I;
if (result < length) {
result = length;
}
}
return result;
}
/**
* 效率太低
* @param s
* @return
*/
public int lengthOfLongestSubstring1(String s) {
int result = 0;
int length = 0;
int nextEndStart = 0;
// 哈希集合,记录每个字符是否出现过
Set<Character> occ = new HashSet<Character>();
for (int i = 0; i < s.length(); i++) {
if (i > 0) {
// 左指针向右移动一格,移除一个字符
occ.remove(s.charAt(i - 1));
}
// 不断向右移动 右指针
for (int end = nextEndStart; end < s.length(); end++) {
if (occ.contains(s.charAt(end))) {
length = end - I;
nextEndStart = end;
break;
}
occ.add(s.charAt(end));
if(end == s.length() - 1){
length = end - i + 1;
}
}
if (result < length) {
result = length;
}
}
System.out.println("result:" + result);
return result;
}
}
复杂度
- 时间复杂度:O(n),其中 n 是字符串长度。
- 空间复杂度:O(∣Σ∣),其中 Σ 表示字符集(即字符串中可以出现的字符),
∣Σ∣ 表示字符集的大小。在本题中没有明确说明字符集,因此可以默认为所有 ASCII 码在 [0,128) 内的字符,即 ∣Σ∣=128。我们需要用到哈希集合来存储出现过的字符,而字符最多有 ∣Σ∣ 个,因此空间复杂度为 O(∣Σ∣)。
好了,今天就到这里,感谢各位看官到这里,不如点个关注吧!
猜你喜欢
- 2025-06-08 Java String类(java string类 contains()方法)
- 2025-06-08 西门子 S7-1200 PLC 数据类型详解
- 2025-06-08 C++标准库string 类的size() 和 length() 区别
- 2025-06-08 什么是 Redis?Redis的数据类型有哪些?Redis应用场景有哪些?
- 2025-06-08 LeetCode 力扣官方题解 | 521. 最长特殊序列Ⅰ
- 2025-06-08 js中的JSON.stringify()方法的用法
- 2025-06-08 bitmap很强大,但要谨慎使用(bitmaps)
- 2025-06-08 刷题LeetCode:5.最长回文子串(求最长回文子序列)
- 2025-06-08 C语言实现超大数乘法(c语言大数相乘)
- 2025-06-08 以太坊源码(06):RLP 机制分析(以太坊源码解读)
- 最近发表
- 标签列表
-
- newcoder (56)
- 字符串的长度是指 (45)
- drawcontours()参数说明 (60)
- unsignedshortint (59)
- postman并发请求 (47)
- python列表删除 (50)
- 左程云什么水平 (56)
- 计算机网络的拓扑结构是指() (45)
- 编程题 (64)
- postgresql默认端口 (66)
- 数据库的概念模型独立于 (48)
- 产生系统死锁的原因可能是由于 (51)
- 数据库中只存放视图的 (62)
- 在vi中退出不保存的命令是 (53)
- 哪个命令可以将普通用户转换成超级用户 (49)
- noscript标签的作用 (48)
- 联合利华网申 (49)
- swagger和postman (46)
- 结构化程序设计主要强调 (53)
- 172.1 (57)
- apipostwebsocket (47)
- 唯品会后台 (61)
- 简历助手 (56)
- offshow (61)
- mysql数据库面试题 (57)