遍历,然后判断子串和目标字符串是否异位相同
/**
* @Auther: Mason
* @Date: 2020/07/14/17:25
* @Description:
*/
// p是要找的字符串
// s是内容。
public class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> list = new LinkedList<>();
if (s.length() < p.length()) return list;
int len = p.length();
char[] chars = p.toCharArray();
Arrays.sort(chars);
for (int i = 0; i <= s.length() - len; i++) {
if (isEquals(s.substring(i, i + len), chars)) {
list.add(i);
}
}
return list;
}
public boolean isEquals(String str1, char[] chars2) {
char[] chars1 = str1.toCharArray();
Arrays.sort(chars1);
for (int i = 0; i < chars1.length; i++) {
if (chars1[i] != chars2[i]) return false;
}
return true;
}
}
使用滑动窗口的方法:
/**
* @Auther: Mason
* @Date: 2020/07/14/20:54
* @Description:
*/
public class Solution {
// 使用滑动窗口的方法:
public List<Integer> findAnagrams(String s, String p) {
List<Integer> res = new LinkedList<>();
if (s.length() < p.length()) return res;
HashMap<Character, Integer> need = new HashMap<>();// 需求哈希表,值为个数
HashMap<Character, Integer> window = new HashMap<>();// 窗口哈希表,值为个数
for (int i = 0; i < p.length(); i++) {
char c = p.charAt(i);
need.put(c, need.getOrDefault(c, 0) + 1);
}
// 已经更新完了need 哈希表。
int valid = 0;
for (int i = 0; i < p.length(); i++) {
char c = s.charAt(i);
window.put(c, window.getOrDefault(c, 0) + 1);
if (window.get(c).equals(need.get(c))) {
valid++;
}
}
if (valid == need.size()) res.add(0);
int left = 0; // 窗口最左边的元素序号
int right = p.length() - 1; // 窗口最右边的序号
while (right < s.length() - 1) {
// 处理右边
right++;
char c = s.charAt(right);
window.put(c, window.getOrDefault(c, 0) + 1);
if (window.get(c).equals(need.get(c))) valid++;
// 处理左边
c = s.charAt(left);
if (need.getOrDefault(c, 0).equals(window.get(c))) valid--;
window.put(c, window.get(c) - 1);
left++;
if (valid == need.size()) {
res.add(left);
}
}
return res;
}
}
使用滑动窗口,但是用数组来代替哈希表。
/**
* @Auther: Mason
* @Date: 2020/07/14/20:54
* @Description:
*/
public class Solution {
// 使用滑动窗口的方法:
public List<Integer> findAnagrams(String s, String p) {
List<Integer> res = new LinkedList<>();
if (s.length() < p.length()) return res;
int[] need = new int[26];
int[] window = new int[26];
for (int i = 0; i < p.length(); i++) {
char c = p.charAt(i);
need[c - 97]++;
}
// 已经更新完了need 数组
int kind = 0;
for (int i = 0; i < 26; i++) {
if (need[i] != 0) kind++;
}
int valid = 0;
for (int i = 0; i < p.length(); i++) {
char c = s.charAt(i);
window[c - 97]++;
if (need[c - 97] == window[c - 97]) {
valid++;
}
}
if (valid == kind) res.add(0);
int left = 0; // 窗口最左边的元素序号
int right = p.length() - 1; // 窗口最右边的序号
while (right < s.length() - 1) {
// 处理右边
right++;
char c = s.charAt(right);
window[c - 97]++;
if (window[c - 97] == need[c - 97]) valid++;
// 处理左边
c = s.charAt(left);
if (window[c - 97] == need[c - 97]) valid--;
window[c - 97]--;
left++;
if (valid == kind) {
res.add(left);
}
}
return res;
}
}