5.15
最开始就是用了两次循环来 依次进行对比 果然超时了。
后来又继续使用了HashMap,AC了。
学会了比较两个map是不是相等,不能直接使用== ,可以使用map.equals(map2)。
超时的 以及AC代码都列出来吧。
public class Solution {
/**
* @param s a string
* @param p a non-empty string
* @return a list of index
*/
//万万没想到,居然超时了,不做了先
public List<Integer> findAnagrams(String s, String p) {
// Write your code here
List<Integer> res = new ArrayList<Integer>();
int a = s.length();
int b = p.length();
if( a < b){
return res;
}
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
HashMap<Character,Integer> map1 = new HashMap<Character,Integer>();
for(int i = 0; i < b;i++){
char tmp = p.charAt(i);
char tmp1 = s.charAt(i);
if(!map.containsKey(tmp)){
map.put(tmp,1);
}
else{
map.put(tmp,map.get(tmp)+1);
}
if(!map1.containsKey(tmp1)){
map1.put(tmp1,1);
}
else{
map1.put(tmp1,map1.get(tmp1)+1);
}
}
//System.out.println("map" + map + ":map1" +map1);
//问题出在判断相等这里
//if(map == map1){
if(map.equals(map1)){
//System.out.println("HERE");
res.add(0);
}
for(int i = 1; i < a-b+1; i++){
//修改HashMap1
char tmp = s.charAt(i-1);
char tmp2 = s.charAt(i+b-1);
if(map1.get(tmp) == 1){
map1.remove(tmp);
}
else{
map1.put(tmp,map1.get(tmp) -1);
}
if(!map1.containsKey(tmp2)){
map1.put(tmp2,1);
}
else{
map1.put(tmp2,map1.get(tmp2) +1);
}
if(map.equals(map1)){
//System.out.println("HERE");
res.add(i);
}
}
return res;
}
/*
public List<Integer> findAnagrams(String s, String p) {
// Write your code here
List<Integer> res = new ArrayList<Integer>();
int a = s.length();
int b = p.length();
if( a < b){
return res;
}
for(int i = 0; i < a-b+1; i++){
String s1 = s.substring(i,i+b);
if(charge(s1,p)){
res.add(i);
}
}
return res;
}
public boolean charge(String s1, String p1){
String tmp = p1;
int length = s1.length();
for(int i = 0;i < length;i++){
if(tmp.contains(Character.toString(s1.charAt(i)))){
tmp = tmp.replaceFirst(Character.toString(s1.charAt(i)),"");
}
else{
return false;
}
}
return true;
}
*/
}