Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 판다스
- 야학
- 카카오클라우드스쿨2기
- Python
- 데이터베이서
- 데이터베이스
- CNN
- 연산자
- 개발자
- 파이썬
- MySQL
- 머신러닝야학
- 이것이 자바다
- 데이터베이스 개론
- flatten
- 생활코딩
- 생활코딩 머신러닝야학
- pandas
- Java
- JavaScript
- 머신러닝
- LeNet
- 머신러닝(딥러닝)
- reshape
- 딥러닝
- Database
- 생활코딩 데이터베이스
- tensorflow
Archives
- Today
- Total
IT's 우
[java] 프로그래머스 - 단어 변환 본문
728x90
https://school.programmers.co.kr/learn/courses/30/lessons/43163
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
사용한 알고리즘
- Hash
- DFS
코드
import java.util.*;
class Solution {
static HashMap<String, ArrayList<String>> map = new HashMap<>();
static boolean checked [];
static String tar;
static String[] ws;
static PriorityQueue<Integer> pr = new PriorityQueue<>();
public int solution(String begin, String target, String[] words) {
int answer = 0;
tar = target;
ws = words;
// HashMap에 각 단어가 한글자만 다른 단어들을 넣어놓기 위하여
map.put(begin, new ArrayList<String>());
// map에 각 단어들을 넣으면서 findWords 메서드를 이용해서 한글자만 다른 단어들을 map에 넣어줬다.
for (String w : words) {
map.put(w, new ArrayList<String>());
findWords(w.toCharArray(), words);
}
// 시작 단어도 넣어줌.
findWords(begin.toCharArray(), words);
// 방문 체크
checked = new boolean[words.length];
// dfs
dfs(begin, 0);
// 변환 과정 중 제일 짧은 수 찾아줌
if (pr.size() != 0) answer = pr.poll();
return answer;
}
// map에 있는 단어들을 방문 확인하여 dfs
public void dfs(String w, int cnt) {
ArrayList<String> list = map.get(w);
cnt++;
for (String s : list) {
int idx = Arrays.asList(ws).indexOf(s);
if (s.equals(tar)) {
pr.add(cnt);
}
else if (checked[idx]) continue;
else {
checked[idx] = true;
dfs(s, cnt);
checked[idx] = false;
}
}
}
// 한글자만 다른 단어들 찾아주기
// 유의할 점 index로 확인해서 한글자만 다른 거 찾아주기
public void findWords(char[] array, String[] words) {
int len = array.length;
int count = 0;
for (String w : words) {
count = 0;
if (w.equals(String.valueOf(array))) continue;
for (int i = 0; i < len; i++) {
if (w.charAt(i) == array[i]) count++;
}
if (count == (len-1)) {
ArrayList<String> list = map.get(String.valueOf(array));
list.add(w);
map.put(String.valueOf(array), list);
}
}
}
}
풀이


문자열 배열에서 문자 인덱스 찾기
:
배열을 리스트로 바꾸고 인덱스를 찾기
String [] array = {"a", "b", "c"};
String str = "a";
int index = Arrays.asList(array).indexOf(arr);
728x90
반응형
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[java] 프로그래머스 - 과제 진행하기 (0) | 2023.05.17 |
---|---|
[java]프로그래머스 - 연속된 부분 수열의 합 (0) | 2023.05.15 |
[java, 프로그래머스] 프로그래머스 - 두 원 사이의 정수 쌍 (0) | 2023.05.12 |
[Java]프로그래머스- 순위(DFS, 깊이 우선 탐색) (0) | 2023.03.22 |
[java, 프로그래머스] 게임 맵 최단거리(Lv.2), BFS 너비 우선 탐색 알고리즘 (0) | 2022.10.26 |