題目描述
給定一個字符串,請你找出其中不含有重復字符的 最長子串 的長度。
示例 1:
輸入: "abcabcbb"
輸出: 3
解釋: 因為無重復字符的最長子串是 "abc",所以其長度為 3。
示例 2:
輸入: "bbbbb"
輸出: 1
解釋: 因為無重復字符的最長子串是 "b",所以其長度為 1。
示例 3:
輸入: "pwwkew"
輸出: 3
解釋: 因為無重復字符的最長子串是 "wke",所以其長度為 3。
請注意,你的答案必須是 子串 的長度,"pwke" 是一個子序列,不是子串。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
題解
我的題解
我的想法:以每個字符為起始查找最長無重復子串,從中找出最長的無重復子串
public static int lengthOfLongestSubstring(String s) {
Set<Character> subSet = new HashSet<>();
int maxlenth = 0;
for (int i = 0; i < s.length(); i++) {
subSet.clear();
for (int j = i; j < s.length(); j++) {
if (subSet.contains(s.charAt(j))){
break;
}
subSet.add(s.charAt(j));
}
maxlenth = Math.max(maxlenth,subSet.size());
}
return maxlenth;
}
這種思路跟官方題解的滑動法有點相似,官方題解還有一種優化滑動法速度很快,所以要好好學算法啊,下面看一下運行結果對比
下面是我的運行效果,上面是官方題解(方法三)的運行效果
官方題解
官方題解給了三種方法:
第一種是暴力法,思路是查找所有子串,找出最長的子串,速度慢的一批,不介紹了,有興趣的上面有鏈接自己去看
第二種是滑動法
思路:
public int lengthOfLongestSubstring(String s) {
int n = s.length();
Set<Character> set = new HashSet<>();
int ans = 0, i = 0, j = 0;
while (i < n && j < n) {
// try to extend the range [i, j]
if (!set.contains(s.charAt(j))){
set.add(s.charAt(j++));
ans = Math.max(ans, j - i);
}
else {
set.remove(s.charAt(i++));
}
}
return ans;
}
復雜度:
第三種是優化滑動法
思路:
public int lengthOfLongestSubstring(String s) {
int n = s.length(), ans = 0;
Map<Character, Integer> map = new HashMap<>(); // current index of character
// try to extend the range [i, j]
for (int j = 0, i = 0; j < n; j++) {
if (map.containsKey(s.charAt(j))) {
i = Math.max(map.get(s.charAt(j)), i);
}
ans = Math.max(ans, j - i + 1);
map.put(s.charAt(j), j + 1);
}
return ans;
}
復雜度: