上一题的进阶,依旧是双指针+哈希表的解法,只是这次遇到结果不要停。
题目链接:https://leetcode.cn/problems/VabMRr
给定两个字符串 s 和 p,找到 s 中所有 p 的 变位词 的子串,返回这些子串的起始索引。不考虑答案输出的顺序。
变位词 指字母相同,但排列不同的字符串。
思路上一题的进阶,因为是要找到多个子串。那么在上一题的基础上,找到第一个子串时不直接返回,而是记录下来起始索引,之后双指针继续右移。
解法:双指针+哈希表 代码public ListfindAnagrams(String s, String p) { List result = new ArrayList<>(); if (p.length() > s.length()) { return result; } int[] counts = new int[26]; for (int i = 0; i < p.length(); i++) { counts[p.charAt(i) - 'a'] += 1; counts[s.charAt(i) - 'a'] -= 1; } if (allZero(counts)) { result.add(0); } for (int i = p.length(); i < s.length(); i++) { counts[s.charAt(i) - 'a'] -= 1; counts[s.charAt(i-p.length()) - 'a'] += 1; if (allZero(counts)) { result.add(i - p.length() + 1); } } return result; } public boolean allZero(int[] counts){ for (int count : counts) { if (count != 0) { return false; } } return true; }



