Algorithm/프로그래머스
[프로그래머스] 외계어 사전 (Java)
Carroti
2022. 10. 21. 17:58
문제
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
알고리즘
해시셋
풀이
spell의 모든 글자를 set에 추가하고,
dic의 각 문자열의 글자가 2번 이상 나오거나 set에 없다면 다음 문자열로 넘어간다.
문자열의 모든 글자가 한 번 나오면서 set에 있다면 1을 출력하고 프로그램을 종료한다.
코드
import java.util.*;
class Solution {
public int solution(String[] spell, String[] dic) {
int answer = 2;
HashSet<Character> set = new HashSet<>();
for(String str: spell)
set.add(str.charAt(0));
label1: for(String str: dic) {
if(str.length() != spell.length) continue;
int[] count = new int[26];
for(int i=0; i<str.length(); i++) {
if(++count[str.charAt(i) - 'a'] == 2) continue label1;
if(!set.contains(str.charAt(i))) continue label1;
}
answer= 1;
break;
}
return answer;
}
}