728x90

하나의 키에 할당된 문자들이 순서대로 담긴 문자열 배열 keymap과 

입력하려는 문자열이 담긴 배열 targets가 주어질때 

하나의 target을 입력하기 위해 키를 총 몇번을 눌러야하는지를 배열로 반환 

public int[] solution(String[] keymap, String[] targets) {

int[] answer = new int[targets.length];

Map<Character,Integer> map = new HashMap<Character, Integer>();

for (int i = 0; i < keymap.length; i++) {

for (int j = 0; j < keymap[i].length(); j++) {

if(map.getOrDefault(keymap[i].charAt(j), 0)==0||map.getOrDefault(keymap[i].charAt(j), 0)>j+1)

map.put(keymap[i].charAt(j), j+1);

}

}

for (int i = 0; i < targets.length; i++) {

int repeat = 0;

for (int j = 0; j < targets[i].length(); j++) {

int temp = map.getOrDefault(targets[i].charAt(j),-1);

if(temp!=-1)

repeat+=temp;

else {

repeat=-1;

break;

}

}

answer[i] = repeat;

 

}

return answer;

}

 map에 입력하려는 문자에 대한 키의 최소 입력횟수를 저장

만약 다른 키에서 동일한 문자의 최소 입력횟수가 더 적을 경우 적은 횟수를 저장 

 

'Java > Coding Test' 카테고리의 다른 글

실패율 문제 풀이  (0) 2023.10.01
문자열 나누기 문제 풀이  (1) 2023.10.01
모의고사 문제 풀이  (0) 2023.09.30
개인정보 수집 유효 기간 문제 풀이  (0) 2023.09.28
숫자 짝궁 문제 풀이  (1) 2023.09.28
728x90

답을 찍는 3가지 패턴과 정답이 주어질 때 

3가지 패턴 중 정답을 가장 많이 맞힌 패턴을 오름차순 정렬하여 반환 

 

public ArrayList<Integer> solution(int[] answers) {

int[] answer = new int[3];

int[] first = { 1, 2, 3, 4, 5 };

int[] second = { 2, 1, 2, 3, 2, 4, 2, 5 };

int[] third = { 3, 3, 1, 1, 2, 2, 4, 4, 5, 5 };

int firstScore = score(first,answers);

int secondScore = score(second,answers);

int thirdScore = score(third,answers);

int max = Math.max(secondScore, thirdScore);

max = Math.max(max, firstScore);

ArrayList<Integer> list = new ArrayList<Integer>();

if(max==firstScore) list.add(1);

if(max==secondScore) list.add(2);

if(max==thirdScore) list.add(3);

return list;

}

 

public int score(int[] person,int[] answers) {

int score = 0;

for (int i = 0; i < answers.length; i++) {

if(answers[i]==person[i%person.length])score++;

}

return score;

}

정답 개수 구하기

==> 패턴이 반복되기 때문에 %(패턴길이)로 패턴길이를 넘어가면 다시 앞으로 돌아와서 비교할 수 있게 한다.

 

최고점 구하여 1번부터 최고점과 같으면 list에 넣어 반환 

 

만약 패턴이 많아진다면

score를 배열에 넣고 정렬로 최고점을 구한 후 

반복문으로 list에 넣어 간결한 코드를 만들 수 있다.

'Java > Coding Test' 카테고리의 다른 글

문자열 나누기 문제 풀이  (1) 2023.10.01
대충 만든 자판 문제 풀이  (0) 2023.10.01
개인정보 수집 유효 기간 문제 풀이  (0) 2023.09.28
숫자 짝궁 문제 풀이  (1) 2023.09.28
옹알이2 문제 풀이  (0) 2023.09.28
728x90

주어진 today 날짜 기준으로 개인정보 수집 유효기간을 초과하여 파기하여야하는 개인정보를 반환 

public ArrayList<Integer> solution(String today, String[] terms, String[] privacies) {

ArrayList<Integer> answer = new ArrayList<Integer>();

for (int i = 0; i < privacies.length; i++) {

String yearStr = privacies[i].substring(0, 4);

String monthStr = privacies[i].substring(5, 7);

String dayStr = privacies[i].substring(8, 10);

int year = Integer.parseInt(yearStr);

int month = Integer.parseInt(monthStr);

int day = Integer.parseInt(dayStr);

String termStr = privacies[i].substring(11);

int term = 0;

for (int j = 0; j < terms.length; j++) {

if (terms[j].startsWith(termStr)) {

term = Integer.parseInt(terms[j].substring(2));

}

}

month = month + term;

if (month > 12) {

year++;

month -= 12;

}

day--;

if (day == 0) {

month--;

if (month == 0) {

year--;

month = 12;

day = 31;

} else if (month == 1) {

day = 31;

} else if (month == 2) {

if (isLuna(year)) {

day = 29;

} else {

day = 28;

}

} else if (month == 3) {

day = 31;

 

} else if (month == 4) {

day = 30;

 

} else if (month == 5) {

day = 31;

 

} else if (month == 6) {

day = 30;

 

} else if (month == 7) {

day = 31;

 

} else if (month == 8) {

day = 31;

 

} else if (month == 9) {

day = 30;

 

} else if (month == 10) {

day = 31;

 

} else if (month == 11) {

day = 30;

 

}

 

}

Date pd = new Date();

String pDate= year+"."+month+"."+day;

try {

pd=new SimpleDateFormat("yyyy.MM.dd").parse(pDate);

Date t = new SimpleDateFormat("yyyy.MM.dd").parse(today);

if(pd.compareTo(t)<0)

answer.add(i+1);

} catch (ParseException e) {

e.printStackTrace();

}

}

return answer;

}

Date 객체로 날짜들을 변환하여 비교하였다. 

 

월별로 일수가 다르기 때문에 월별로 조건문을 이용해 일수를 다르게 지정해주는 바람에 코드가 길어졌다. 

 

하지만 날짜의 대소를 비교할때는 굳이 날짜 형식을 지켜주지 않아도 일수가 많은지 적은지만 비교하면 된다. 

 

public ArrayList<Integer> solution2(String today, String[] terms, String[] privacies) {

ArrayList<Integer> answer = new ArrayList<Integer>();

int tday =Integer.parseInt(today.substring(0,4))*12*28+Integer.parseInt(today.substring(5,7))*28+Integer.parseInt(today.substring(8,10));

 

for (int i = 0; i < privacies.length; i++) {

String termStr = privacies[i].substring(11);

int term = 0;

for (int j = 0; j < terms.length; j++) {

if (terms[j].startsWith(termStr)) {

term = Integer.parseInt(terms[j].substring(2));

}

}

String yearStr = privacies[i].substring(0, 4);

String monthStr = privacies[i].substring(5, 7);

String dayStr = privacies[i].substring(8, 10);

int year = Integer.parseInt(yearStr);

int month = Integer.parseInt(monthStr);

int day = Integer.parseInt(dayStr);

month = month + term;

int n = day+month*28+year*28*12;

if(n<=tday)

answer.add(i+1);

}

return answer;

}

이렇게 계산하니까 시간도 엄청 단축되었다.

'Java > Coding Test' 카테고리의 다른 글

대충 만든 자판 문제 풀이  (0) 2023.10.01
모의고사 문제 풀이  (0) 2023.09.30
숫자 짝궁 문제 풀이  (1) 2023.09.28
옹알이2 문제 풀이  (0) 2023.09.28
과일 장수 문제 풀이  (0) 2023.09.28
728x90

두 문자열이 포함하고 있는 수들 중 공통으로 가지고 있는 수를 이용하여 만들 수 있는 가장 큰 수

public String solution(String X, String Y) {

StringBuilder answer = new StringBuilder();

int[] cArr = new int[10];

for (int i = 0; i < cArr.length; i++) {

int xlen = X.length();

int ylen = Y.length();

X = X.replaceAll(i+"", "");

Y = Y.replaceAll(i+"", "");

xlen = xlen-X.length();

ylen = ylen-Y.length();

if(xlen>0&&ylen>0) {

cArr[i] = Math.min(xlen, ylen);

}

}

for (int i = 0; i < cArr.length; i++) {

int num = cArr[cArr.length-1-i];

if(num!=0) {

String add = (9-i)+"";

answer.append(add.repeat(num));

}

}

if(answer.length()==0)return "-1";

if(answer.charAt(0)=='0')return "0";

return answer.toString();

}

X,Y의 길이가 3백만까지 제한되어있고, 0으로 시작하지 않는 제한 조건이 있다. 

길이 문제로 시간초과, int타입 제한에 문제가 발생할 수 있다. 

시간초과 문제를 해결하기 위해 StringBuilder를 사용하였고 

""과 "0.."등을 확인할 때

정수형 타입의 길이 제한을 피하기 위해 toString으로 변환한 뒤 확인하려하면 overflow의 문제가 발생하므로 

length 와 charAt메서드를 사용하여 확인하였다. 

'Java > Coding Test' 카테고리의 다른 글

모의고사 문제 풀이  (0) 2023.09.30
개인정보 수집 유효 기간 문제 풀이  (0) 2023.09.28
옹알이2 문제 풀이  (0) 2023.09.28
과일 장수 문제 풀이  (0) 2023.09.28
2016년 문제 풀이  (0) 2023.09.28

+ Recent posts