728x90
문제
제한사항
- 1 ≤ s의 길이 ≤ 50
- s가 "zero" 또는 "0"으로 시작하는 경우는 주어지지 않습니다.
- return 값이 1 이상 2,000,000,000 이하의 정수가 되는 올바른 입력만 s로 주어집니다.
s | result |
"one4seveneight" | 1478 |
"23four5six7" | 234567 |
"2three45sixseven" | 234567 |
"123" | 123 |
풀이
class Solution {
public int solution(String s) {
int answer = 0;
String[] num = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
for (int i=0; i<num.length; i++) {
s = s.replace(num[i], Integer.toString(i));
}
answer = Integer.parseInt(s);
return answer;
}
}
배열에 문자열을 넣은 다음, 인덱스에 해당하는 숫자를 교체하는 방식으로 진행하였다. 코드를 제출할 때는 String의 replace 메소드를 이용하였는데, 정답을 확인하고 다른 사람의 풀이를 보니 replaceAll을 써서 제출한 사람도 보였다. 이 둘의 차이가 궁금하여 Java API를 검색해 보았다.
String.replace()와 String.replaceAll()의 차이는 뭘까?
String.replace()
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
replace() 메소드는 오버로딩이 2개 되어 있다. 문자 하나인 char형을 다른 문자 하나로 바꿔주거나, 문자열의 인터페이스인 CharSequence를 다른 문자열로 교체하는 방식이 있다.
String.replaceAll()
Replaces each substring of this string that matches the given regular expression with the given replacement.
replaceAll() 메소드는 정규식을 사용하여 특정 패턴을 다른 문자열로 교체하는 역할을 한다.
문제를 풀기 전에 가끔씩 API 문서를 보는 습관을 들여야겠다. 내가 알고 있는 메소드에 대한 설명도 확실히 짚고 가고, 헷갈리는 부분 또한 설명이 되어 있기 때문이다.
출처: 프로그래머스 코딩테스트 연습, https://school.programmers.co.kr/learn/courses/30/lessons/81301
728x90
'코딩테스트 연습 > Programmers' 카테고리의 다른 글
[프로그래머스] 문자열 내림차순으로 배치하기 (1) | 2024.04.01 |
---|---|
[프로그래머스] 크기가 작은 부분문자열 (0) | 2024.03.31 |
[프로그래머스] 부족한 금액 계산하기 (1) | 2024.03.29 |
[프로그래머스] 최댓값과 최솟값 (0) | 2024.03.27 |
[프로그래머스] 두 정수 사이의 합 (1) | 2024.03.26 |