public int solution(String a, String b){
int answer = 0;
HashMap<Character,Integer> am = new HashMap<>();
HashMap<Character,Integer> bm = new HashMap<>();
}
입력값이 bacaAacaa이고, abc와 아나그램인 문자열을 찾기 위해서는,
입력값1의 문자 2개를 Map에 저장한다.
for(char x : b.toCharArray())
bm.put(x, bm.getOrDefault(x, 0)+1);
int L = b.length()-1;
for(int i=0;i<L;i++){
am.put(a.charAt(i), am.getOrDefault(a.charAt(i),0)+1);
}
int lt = 0;
for(int rt = L; rt<a.length(); rt++){
am.put(a.charAt(rt), am.getOrDefault(a.charAt(rt),0)+1);
if(am.equals(bm)) answer++;
}
am.put(a.charAt(lt), am.get(a.charAt(lt))-1);
if(am.get(a.charAt(lt))==0) am.remove(a.charAt(lt));
lt와 rt의 값을 하나씩 증가시킨 후, 입력값1[rt] 의 값을 Map am에 추가한다.
lt++
package algolecture;
import java.util.HashMap;
import java.util.Scanner;
public class Main34 {
public int solution(String a, String b){
int answer = 0;
HashMap<Character,Integer> am = new HashMap<>();
HashMap<Character,Integer> bm = new HashMap<>();
// b 세팅하기
for(char x : b.toCharArray())
bm.put(x, bm.getOrDefault(x, 0)+1);
int L = b.length()-1;
for(int i=0;i<L;i++){
am.put(a.charAt(i), am.getOrDefault(a.charAt(i),0)+1);
}
int lt = 0;
for(int rt = L; rt<a.length(); rt++){
am.put(a.charAt(rt), am.getOrDefault(a.charAt(rt),0)+1);
if(am.equals(bm)) answer++;
am.put(a.charAt(lt), am.get(a.charAt(lt))-1);
if(am.get(a.charAt(lt))==0) am.remove(a.charAt(lt));
lt++;
}
return answer;
}
public static void main(String[] args) {
Main34 T = new Main34();
Scanner kb = new Scanner(System.in);
String a = kb.next();
String b = kb.next();
System.out.print(T.solution(a,b));
}
}