无重复字符串的最长子串
https://leetcode.cn/problems/longest-substring-without-repeating-characters/?envType=study-plan-v2&envId=top-100-liked
class Solution {
public int lengthOfLongestSubstring(String s) {
int max = 0;
int left = 0;
HashMap<Character, Integer> map = new HashMap<>();
for(int i = 0; i < s.length(); i++){
if(map.containsKey(s.charAt(i))){
left = Math.max(left, map.get(s.charAt(i)) + 1);
}
max = Math.max(i - left + 1, max);
map.put(s.charAt(i), i);
}
return max;
}
}
关键:
- 用hashMap记录,key:字符,value:下标
- 当遇到重复元素的时候,不断更新left,然后i-left+1不断更新,就得到不重复的最长子串。
找到字符串中所有的字母异位词
https://leetcode.cn/problems/find-all-anagrams-in-a-string/
class Solution {
public List<Integer> findAnagrams(String s, String p) {
int[] num = new int[26];
int[] tar = new int[26];
List<Integer> list = new LinkedList<>();
int left = 0, right = 0;
for(int i = 0; i < p.length(); i ++){
num[p.charAt(i) - 'a']++;
}
while(right < s.length()){
tar[s.charAt(right) - 'a'] ++;
if(right - left + 1 == p.length()){
if(Arrays.equals(tar, num)){
list.add(left);
}
tar[s.charAt(left) - 'a'] --;
left++;
}
right++;
}
return list;
}
}
关键点:
- 用两个数组记录字符串中的字符以及字符的个数,然后通过left,right指针的移动,找到两个数组相等的下标。
- Arrays.equals(tar, num)这个Api容易忘记。