给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引。
字符串只包含小写英文字母,并且字符串 s 和 p 的长度都不超过 20100。
说明:
- 字母异位词指字母相同,但排列不同的字符串。
- 不考虑答案输出的顺序。
示例 1:
输入:
s: "cbaebabacd" p: "abc"
输出:
[0, 6]
解释:
起始索引等于 0 的子串是 "cba", 它是 "abc" 的字母异位词。
起始索引等于 6 的子串是 "bac", 它是 "abc" 的字母异位词。
示例 2:
输入:
s: "abab" p: "ab"
输出:
[0, 1, 2]
解释:
起始索引等于 0 的子串是 "ab", 它是 "ab" 的字母异位词。
起始索引等于 1 的子串是 "ba", 它是 "ab" 的字母异位词。
起始索引等于 2 的子串是 "ab", 它是 "ab" 的字母异位词。
class Solution {
public boolean isSame(Map<Character,Integer> map1,Map<Character,Integer> map2){
//遍历map1 看看map1中的元素是否都在map2 中且值相等
Set<Character> keys = map1.keySet();
Iterator<Character> it = keys.iterator();
while(it.hasNext()){
char c =it.next();
if(!map2.containsKey(c)){
return false;
}else if(!map1.get(c).equals(map2.get(c))){// 这里一定要注意 integer 的
//常量池为【-128,127】不要用==
return false;
}
}
return true;
}
public void addmap(Map<Character,Integer> map,char a){//向map中添加元素
if(map.containsKey(a)){
map.put(a,map.get(a)+1);
}else{
map.put(a,1);
}
}
public List<Integer> findAnagrams(String s, String p) {
List<Integer> ans = new ArrayList<>();
if(s.length()<p.length()){
return ans;
}
System.out.println("s.length():"+s.length());
System.out.println("p.length():"+p.length());
Map<Character,Integer> map1 = new HashMap<>();
for(char a:p.toCharArray()){
addmap(map1,a); //构造p的映射表,方便窗口map2查找
}//end of for
Map<Character,Integer> map2 = new HashMap<>();
for(int i =0; i<p.length()-1;i++){
char z = s.charAt(i);
addmap(map2,z);//事先将S的前p.length()-1个元素写入窗口
}
for(int i = p.length()-1;i<s.length();i++){
char c = s.charAt(i);//窗口尾元素
char d = s.charAt(i-p.length()+1);//即将要移出去的元素(左)
addmap(map2,c);
if(isSame(map1,map2)){
ans.add(i-p.length()+1);//窗口中的元素与map1 相同 就add list
}
map2.put(d,map2.get(d)-1); //左边界移动 ,移动窗口(p.length)
}
return ans;
}
}
写后发现这个方法时间耗费大:
然后发现大牛:
下面是数组 :这
class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> ans = new ArrayList<>();
if (s.length() < p.length()) {
return ans;
}
int[] dict = new int[26];
for (char c : p.toCharArray()) {
dict[c - 'a']++;
}
int[] cur = new int[26];
for (int i = 0; i < p.length() - 1; i++) {
cur[s.charAt(i) - 'a']++;
}
for (int i = p.length() - 1; i < s.length(); i++) {
cur[s.charAt(i) - 'a']++;
if (isSame(dict, cur)) {
ans.add(i - p.length() + 1);
}
cur[s.charAt(i - p.length() + 1) - 'a']--;
}
return ans;
}
private boolean isSame(int[] a, int[] b) {
for (int i = 0; i < 26; i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
}