LeeCode热题 100打卡第六天
第一道题
无重复字符的最长字串(LeeCode第三题):
给定一个字符串 `s`,请你找出其中不含有重复字符的最长子串的长度。
class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> set = new HashSet<>();
int n = s.length();
int r = -1;
int ans = 0;
for(int i = 0;i < n; i++){
if(i != 0){
set.remove(s.charAt(i - 1));
}
while(r + 1 < n && !set.contains(s.charAt(r + 1))){
set.add(s.charAt(r + 1));
r++;
}
ans = Math.max(ans, r - i + 1);
}
return ans;
}
}
第二道题
找到字符串中所有字母异位词(LeeCode第438题):
给定两个字符串 s 和 p,找到 s 中所有 p 的 异位词 的子串,返回这些子串的起始索引。不考虑答案输出的顺序。异位词: 指由相同字母重排列形成的字符串(包括相同的字符串)。
具体解法:1.首先记录p中每个字符出现的次数(这个地方用到了ASCII码的相关知识)2.构造固定大小的窗口,这个窗口的大小应与字符串p的大小相同
class Solution {
public List<Integer> findAnagrams(String s, String p) {
ArrayList<Integer> list= new ArrayList<Integer>();
int slen = s.length(),plen = p.length();
if(plen > slen) return list;
int[] arrs = new int[26];
int[] arrp = new int[26];
for (int i = 0; i < plen; i++){
arrs[s.charAt(i) - 'a'] += 1;
arrp[p.charAt(i) - 'a'] += 1;
}
if(Arrays.equals(arrs, arrp)){
list.add(0);
}
for(int i = 1; plen + i - 1 < slen; i++){
arrs[s.charAt(i - 1) - 'a'] -=1;
arrs[s.charAt(plen + i - 1) - 'a'] +=1;
if(Arrays.equals(arrs, arrp)){
list.add(i);}
}
return list;
}
}