[LeetCode]3.无重复字符的最长子串
自己的解法
将字符串转化为字符数组,从首字符向后扫描字串,找到不重复的最长字串
class Solution {
public int lengthOfLongestSubstring(String s) {
char[] chars = s.toCharArray();
HashSet<Character> hs = new HashSet();
int size = 0;
for(int j = 0; j < chars.length; j++){
for(int i = j; i < chars.length; i++){
if(hs.contains(chars[i])){
break;
}
hs.add(chars[i]);
}
if(size < hs.size()){
size = hs.size();
}
hs.clear();
}
return size;
}
}
滑动窗口
class Solution {
public int lengthOfLongestSubstring(String s) {
HashSet<Character> hs = new HashSet<>();
int i = 0, j= 0;
int n = s.length();
int ans = 0;
while( i < n && j < n){
if(!hs.contains(s.charAt(j))){
hs.add(s.charAt(j++));
ans = Math.max(ans, j - i);
}
else{
hs.remove(s.charAt(i++));
}
}
return ans;
}
}
优化滑动窗口
class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
int ans = 0;
Map<Character,Integer> map = new HashMap<>();
for(int i = 0, j = 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;
}
}
假设字符集为 ASCII 128
class Solution {
public int lengthOfLongestSubstring(String s) {
int[] index = new int[128];
int n = s.length();
int ans = 0;
for(int i=0, j = 0; j < n; j++){
i = Math.max(index[s.charAt(j)],i);
ans = Math.max(ans,j-i+1);
index[s.charAt(j)] = j+1;
}
return ans;
}
}