给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。
示例 1:
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
一,暴力法,直接两个for循环遍历字符串
class Solution {
public static int lengthOfLongestSubstring(String s) {
int start, end;
int count = 0;
String str = null;
for (start = 0; start < s.length(); start++) {
for (end = start + 1; end <= s.length(); end++) {
str = s.substring(start, end);
// 先判断是否遍历完
if (end == s.length()) {
count = Math.max(count, str.length());
break;
} else {
// 如果end对应的字符在str字符串中,就终止start对应的循环
// 找到最长的子串保存到count
if (str.contains(s.substring(end, end + 1))) {
count = Math.max(count, str.length());
break;
}
}
}
}
return count;
}
}
方法一时间复杂度是O(n^2), 思路很简单就是用两个指针遍历字符串,找到有相同字符时就重新赋值最长子串的长度。缺点是时间复杂度高!
二,利用HashMap实现滑动窗口
思路:
- 定义一个map数据结构存储(k,v),其中key值为字符,value值为字符位置+1,加1表示从字符位置后一个才开始不重复;
- 我们定义不重复子串的开始位置为start,结束位置为end;
- 随着end不断遍历向后,会遇到与[start, end]区间内字符相同的情况,此时将字符作为key值,获取其value值,然后更新start,此时[start, end]区间内不存在重复字符;
- 最后无论是否更新start,都会更新其map集合和结果ans,map是将s字符串对应的字符值存为key,ans是一直取最大的ans值。
时间复杂度是O(n)
class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length(), ans = 0;
Map<Character, Integer> map = new HashMap<>();
for (int end = 0, start = 0; end < n; end++) {
char alpha = s.charAt(end);
// 判断map集合中是否存在end对应的字符
if (map.containsKey(alpha)) {
start = Math.max(map.get(alpha), start);
}
// 更新and和map的值
ans = Math.max(ans, end - start + 1);
map.put(s.charAt(end), end + 1);
}
return ans;
}
}
有问题欢迎留言哦
参考:
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/
https://draw.mdnice.com/algorithm/3.html