728x90
굉장히 쉽죠
01 내코드
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String code = sc.next();
String lastFourWords = code.substring(code.length()-4, code.length());
if(lastFourWords.equals("_eye")){
System.out.println("Ophthalmologyc");
}
else if(lastFourWords.equals("head")){
System.out.println("Neurosurgery");
}
else if(lastFourWords.equals("infl")){
System.out.println("Orthopedics");
}
else if(lastFourWords.equals("skin")){
System.out.println("Dermatology");
}
else{
System.out.println("direct recommendation");
}
}
}
02 다른사람 코드
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String code = sc.next();
String lastFourWords = code.substring(code.length()-4, code.length());
if(lastFourWords.equals("_eye")){
System.out.println("Ophthalmologyc");
}
else if("head".equals(lastFourWords)){
System.out.println("Neurosurgery");
}
else if("infl".equals(lastFourWords)){
System.out.println("Orthopedics");
}
else if("skin".equals(lastFourWords)){
System.out.println("Dermatology");
}
else{
System.out.println("direct recommendation");
}
}
}
- Null 안전성:
다른 사람의 코드에서 사용한 "head".equals(lastFourWords) 방식은 lastFourWords가 null일 경우에도 NullPointerException을 방지합니다. 내 코드에서는 lastFourWords가 null일 경우 예외가 발생할 수 있습니다.
- 효율성:
두 코드 모두 substring을 사용하여 마지막 네 글자를 추출하는 부분은 동일하므로 성능 차이는 없습니다. 문자열 비교는 평균적으로 O(n)의 시간 복잡도를 가집니다. 두 코드 모두 동일한 비교 방식이므로 성능에 큰 차이는 없습니다.
- 결론!
null 체크 까지 고려하자!
728x90
'주니어 기초 코딩공부 > JAVA_programmers_코딩테스트' 카테고리의 다른 글
[PCCE] 프로그래머스 자바 기초 05 심폐소생술 (0) | 2024.09.22 |
---|---|
[PCCE] 프로그래머스 자바 기초 01 문자 출력 (0) | 2024.09.19 |
자바 HashSet을 활용한 문제 풀이 (0) | 2023.07.07 |
자연수 뒤집어 배열로 만들기_programmers_lev01_str.charAt() (0) | 2023.07.01 |
문자열 내 p와 y의 개수_programmers_lev01_toCharArray (2) | 2023.06.30 |