: 특수문자 포함 여부를 처음에는 contains() 함수를 사용했는데, 정규식 사용하려면 matches() 함수를 사용해야함.
https://lnsideout.tistory.com/entry/JAVA-%EC%9E%90%EB%B0%94-%ED%8A%B9%EC%A0%95-%EB%AC%B8%EC%9E%90%EC%97%B4-%ED%8F%AC%ED%95%A8-%ED%99%95%EC%9D%B8-%EB%B0%8F-%EC%B0%BE%EA%B8%B0containsindexofmatches
리팩토링이 충분히 가능해보이는 코드
함수 추출로 중복 없앨 수 있을 듯.
import java.util.*;
class Solution {
public int solution(String str1, String str2) {
//모두 대문자로 만들기
str1 = str1.toUpperCase();
str2 = str2.toUpperCase();
//조건에 맞춰 두글자씩 끊어서 리스트에 담기
List<String> list1 = new ArrayList<>();
for(int i=0; i<str1.length()-1; i++){
String temp = str1.substring(i, i+2);
if(!temp.matches("^[A-Z]*$")){
continue;
} else {
list1.add(temp);
}
}
List<String> list2 = new ArrayList<>();
for(int i=0; i<str2.length()-1; i++){
String temp = str2.substring(i, i+2);
if(!temp.matches("^[A-Z]*$")){
continue;
} else {
list2.add(temp);
}
}
//교집합, 합집합 크기 구하기
int intersectionCount = 0;
int unionCount = list1.size()+list2.size();
for(int i=0; i<list1.size(); i++){
String str = list1.get(i);
int size = list2.size();
for(int j=0; j<size; j++){
if(list2.get(j).equals(str)){
intersectionCount++;
list2.remove(list2.get(j));
break;
}
}
}
unionCount -= intersectionCount;
if(intersectionCount==0 && unionCount==0){
return 65536;
}
//리턴 = 교집합 크기 / 합집합 크기 * 65536 의 정수 부분
double num = (double) intersectionCount / unionCount;
return (int) Math.floor(num * 65536);
}
}
: 맨 처음에 몇 개의 테스트에서 시간초과 뜨길래, 약수 개수 구하는 부분을 Math.sqrt() 함수를 이용하여 시간 복잡도를 개선했더니 통과.
class Solution {
public int solution(int number, int limit, int power) {
int answer = 0;
//1~number번호 까지의 기사단원의 약수 개수 구하기 -> 해당 개수의 공격력 사용
for(int i=1; i<=number; i++){
int attackCount = getAttackCount(i);
if(attackCount>limit){
answer += power;
} else {
answer += attackCount;
}
}
return answer;
}
public static int getAttackCount(int number){
int count = 0;
int num = (int) Math.sqrt(number);
for(int i=1; i<=num; i++){
if(number%i==0){
count++;
}
}
return Math.sqrt(number)==num ? count*2-1 :count*2;
}
}