Algorithm/Programmers
[프로그래머스] 영어 끝말잇기
Pawer0223
2020. 4. 5. 14:29
문제 링크 : https://programmers.co.kr/learn/courses/30/lessons/12981
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
코드
package Programmers.Level2;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class WordChain {
public static void main(String[] args) {
String[] words = {
"hello","one","even","never","now","world","draw"
};
int n = 2;
int[] result = solution(n, words);
System.out.println(Arrays.toString(result));
}
public static int[] solution(int n, String[] words) {
int[] peoples = new int[n+1];
int peopleIndex = 0;
Map<String, Integer> duplicate = new HashMap<String,Integer>();
char prevChar = words[0].charAt(0);
for ( int i = 0 ; i < words.length; i++ ) {
if(i%n == 0) peopleIndex = 0;
peopleIndex++;
peoples[peopleIndex]++;
char nextChar = words[i].charAt(0);
if( prevChar == nextChar && duplicate.get(words[i]) == null ) {
duplicate.put(words[i],i);
prevChar = words[i].charAt(words[i].length()-1);
}else {
return new int[] { peopleIndex, peoples[peopleIndex] } ;
}
}
return new int[] { 0, 0 } ;
}
// Arrays.asList의 contains를 활용
// java.util.ArrayList 클래스와는 다른 클래스이다.
// java.util.Arrays.ArrayList 클래스는 set(), get(), contains() 메서드를 가지고 있지만 원소를 추가할수 없어서 사이즈를 변경할 수 없다.
private static int[] solution2(int n, String[] words) {
String[] temp = new String[words.length];
char prevChar = words[0].charAt(0);
for ( int i = 0 ; i < words.length; i ++ ) {
char nextChar = words[i].charAt(0);
if ( prevChar != nextChar || Arrays.asList(temp).contains(words[i]) ) {
return new int[] { (i%n)+1 , (i/n)+1 } ;
}else {
temp[i] = words[i];
prevChar = words[i].charAt(words[i].length()-1);
}
}
return new int[] {0,0};
}
}
제출 결과
후기
중복되는 값을 체크하고, 이전단어의 끝 문자와 현재단어의 앞 문자만 기억해서 비교만해주면 알고리즘으로 크게 어렵지 않았다고 생각된다.
처음에는 기존에 나온 단어를 체크하기위해서 Map을 사용해서 key값으로 구분해 주었다. ( solution )
다른사람의 풀이를보고 주어진 배열을 순서대로 처리하는 과정에서 이전에 나왔던 값인지 확인할 수 있는 새로운 방법을 배웠다. ( solution2 )
java.util.Arrays.ArrayList클래스를 활용하는것인데, 이것은 java.util.ArrayList와는 다르다.
해당 클래스는 contains메서드로 리스트에 포함되어있는 요소를 확인할 수 있는데, 주어진 문자열배열 words[]를 순서대로 처리하면서 temp[]에 담아준다.
그리고 String[] temp를 asList로 java.util.Arrays.ArrayList로 변환 후, contains로 현재 넣고자하는 값이 배열에 있는지 확인해주면 된다.
물론.. 이전 값을 계속해서 temp에 추가해주는 작업이 필요하지만, 컬렉션프레임워크를 사용하지 않고도 중복을 확인할 수 있는 새로운 방법을 배울 수 있었다..!
반응형