给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 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 class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
int ans = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j <= n; j++)
if (allUnique(s, i, j)) ans = Math.max(ans, j - i);
return ans;
}
public boolean allUnique(String s, int start, int end) {
Set<Character> set = new HashSet<>();
for (int i = start; i < end; i++) {
Character ch = s.charAt(i);
if (set.contains(ch)) return false;
set.add(ch);
}
return true;
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/wu-zhong-fu-zi-fu-de-zui-chang-zi-chuan-by-leetcod/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
下面是我的理解:
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s == null) return 0;
int maxl = 0;
for(int i = 0;i<s.length();i++){
for(int j= i+1;j<=s.length();j++){
if(boolallunique(s,i,j)) maxl = Math.max(maxl,j-i);
}
}
return maxl;
}
public boolean boolallunique(String s,int start, int end){
Set<Character> list = new HashSet<>();
for(int i= start;i<end;i++){
Character instance = s.charAt(i);
if(list.contains(instance)) return false;
list.add(instance);
}
return true;
}
看来是出问题了,官方给的答案也出不来,虚惊一场,还以为我写的代码计算机也要识别不了了哈哈。
10分钟后~~
我人要傻掉了,原来还真的是时间超时了,时间复杂度O(n3)了,就有可能会出现这种情况嘛?
所以,推荐大家使用解法二,移动区间
解法二:
class Solution {
public int lengthOfLongestSubstring(String s) {
int ans = 0;
int i=0,j=0;
Set<Character> list = new HashSet<>();
while(i<s.length()&&j<s.length()){
if(!list.contains(s.charAt(j))){
list.add(s.charAt(j++));
ans = Math.max(ans,j-i);
}
else{
list.remove(s.charAt(i++));
}
}
return ans;
}
}
舒服了,明天来看第三种解法哈哈。