Sliding Window, HashMap, Two Pointer_모든 아나그램 찾기
✅ S문자열과 T문자열이 주어집니다. T문자열이 S부분문자열의 아나그램이 되는 개수를 구하세요.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Main {
public int solution(String s, String t){
int answer= 0;
HashMap<Character, Integer> mapS= new HashMap<>();
HashMap<Character, Integer> mapT= new HashMap<>();
for(char x: t.toCharArray()){
mapT.put(x, mapT.getOrDefault(x, 0)+1);
}
for(int i=0; i<t.length()-1; i++){
mapS.put(s.charAt(i), mapS.getOrDefault(s.charAt(i), 0)+1);
}
int lt=0;
for(int rt=t.length()-1; rt<s.length(); rt++){
mapS.put(s.charAt(rt), mapS.getOrDefault(s.charAt(rt), 0)+1);
//compare
if(mapS.equals(mapT)) answer++; //compare two hashmaps
//remove the first letter
mapS.put(s.charAt(lt), mapS.get(s.charAt(lt))-1);
if(mapS.get(s.charAt(lt)) ==0) mapS.remove(s.charAt(lt));
lt++;
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc= new Scanner(System.in);
String s= sc.next();
String t= sc.next();
System.out.print(T.solution(s, t));
}
}
//⭐️input:
// bacaAacba
// abc
//⭐️output:
//3
//출력설명: {bac}, {acb}, {cba} 3개의 부분문자열이 "abc"문자열과 아나그램입니다.
🔵 ThingsILearned
✔️ 이전 문제랑 거의 비슷한데, 두 hashmap을 비교하는 방법을 몰라서 엄청 헤메었다.
두 hashmap을 비교하는 방법: equals()
✔️ 하나의 hashmap과 하나의 string을 비교하기는 어렵다.
따라서 string을 hashmap으로 만들어서 두 hashmap끼리 비교
This post is licensed under CC BY 4.0 by the author.