leetcode 438

31 阅读1分钟

声明:个人小菜鸡学习记录,非什么编程知识干货

438. 找到字符串中所有字母异位词 - 力扣(LeetCode)

image.png

重点记住这个代码怎么写,这么优雅的代码最好背下来,自己写的很乱。思路其实不难

class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> ans = new ArrayList<>();
        int[] cnt = new int[26]; // 用数组来作为26个字母的哈希表
        for (char c : p.toCharArray()) { // 遍历p串中每个字母,并计数
            cnt[c - 'a']++;
        }
        int left = 0; // 左指针
        for(int right = 0; right < s.length(); right++) {
            int c = s.charAt(right) - 'a';
            cnt[c]--; // 进来新的字母,抵消--
            while(cnt[c] < 0) { // 字母c太多了,开始让左窗口右移
                cnt[s.charAt(left) - 'a']++; // 把刚开始遍历窗口时抵消的字母还回去
                left++; 
            }
            // 如果窗口大小等于p串长度说明此时已经满足要求,因为上面的循环左指针右移确保了不会有多余的字母
            if(right - left + 1 == p.length()) { 
                ans.add(left);
            }
        }
        return ans;
    }
}