728x90
반응형
SMALL
1. 모음 사전
완전탐색을 했더니 1점을 받았다..
public class Solution {
StringBuilder stack = new StringBuilder();
int n = 0;
String[] alpha = {"A", "E", "I", "O", "U"};
int answer;
public int solution(String word) {
dfs(word);
return answer;
}
private int dfs(String word) {
if (stack.length() == 5) {
if (word.equals(new String(stack))) answer = n;
n++;
}
else {
for (int i = 0; i < 5; i++) {
if (i == 0) {
if (word.equals(new String(stack))) answer = n;
n++;
}
stack.append(alpha[i]);
dfs(word);
stack.deleteCharAt(stack.length() - 1);
}
}
return -1;
}
}
2. 다음 큰 숫자
public class Solution {
public int solution(int n) {
int next = n + 1;
while (numberOfOne(n) != numberOfOne(next)) {
next++;
}
return next;
}
private long numberOfOne(int n) {
String binary = Integer.toBinaryString(n);
return binary.chars().map(i -> i - '0').filter(i -> i == 1).count();
}
}
정확성은 합격이지만 시간초과가 난다.
public class Solution {
public int solution(int n) {
int next = n + 1;
while (Integer.bitCount(n) != Integer.bitCount(next)) next++;
return next;
}
}
Integer 에 bitCount 라는 함수가 존재했고 이것은 2진수의 1의 갯수를 반환한다고 한다.
이 메서드를 사용하니 시간초과가 나지않고 코드도 더 간단해졌다.
728x90
반응형
LIST
'Algorithm > 기타' 카테고리의 다른 글
Lv2 - page 2 (0) | 2022.03.01 |
---|---|
Lv2 - page 1 (0) | 2022.02.26 |
Lv2 - page 4 (0) | 2022.02.26 |
Java kit (0) | 2022.02.23 |
프로그래머스 Lv1 3페이지 (0) | 2022.02.23 |