Leetcode 3. Longest Substring Without Repeating Characters
题目链接: Longest Substring Without Repeating Characters
难度:Medium
题目大意:
求字符串中没有重复字符字串的最长长度。
思路:
这篇博文总结的很全面。
思路1:
暴力,两层for循环来遍历所有可能的字串,碰到有重复字符的子串就提前结束。
思路2:
滑动窗口,如果字串中不包含这个字符,则将字串的结束位置向后移一位继续遍历,否则将字串的开始位置向后移一位。
代码
思路1代码:
class Solution {
public int lengthOfLongestSubstring(String s) {
int max=0;
for(int i=0;i<s.length();i++){
Set<Character> set=new HashSet<Character>();
set.add(s.charAt(i));
for(int j=i+1;j<s.length();j++){
if(!set.contains(s.charAt(j))){
set.add(s.charAt(j));
}
else{
break;
}
}
max=Math.max(max,set.size());
}
return max;
}
}
思路2代码:
class Solution {
public int lengthOfLongestSubstring(String s) {
int max=0;
int n=s.length();
Set<Character> set=new HashSet<Character>();
int i=0,j=0;
while(i<n&&j<n){//i和j分别表示不含重复字符的字符串的开始位置和结束位置
if(!set.contains(s.charAt(j))){
set.add(s.charAt(j));
j++;
}
else{
set.remove(s.charAt(i));
i++;
}
max=Math.max(max,j-i);
}
return max;
}
}