| 문제 | 레벨 | 정답률 |
|---|---|---|
| 숫자 문자열과 영단어 | Lv.1 | 71% |

import java.util.*;
class Solution {
public int solution(String s) {
HashMap<String, Integer> hashMap = new HashMap<>();
String result = "";
hashMap.put("zero", 0);
hashMap.put("one", 1);
hashMap.put("two", 2);
hashMap.put("three", 3);
hashMap.put("four", 4);
hashMap.put("five", 5);
hashMap.put("six", 6);
hashMap.put("seven", 7);
hashMap.put("eight", 8);
hashMap.put("nine", 9);
String str = "";
for(int i = 0; i<s.length(); i++){
if(Character.isDigit(s.charAt(i))){
result+=s.charAt(i);
} else{
str += s.charAt(i);
if(hashMap.containsKey(str)){
result += hashMap.get(str);
str = "";
}
}
}
return Integer.parseInt(result);
import java.util.*;
class Solution {
public int solution(String s) {
// 숫자 단어와 대응하는 정수를 저장할 HashMap 생성
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("zero", 0);
hashMap.put("one", 1);
hashMap.put("two", 2);
hashMap.put("three", 3);
hashMap.put("four", 4);
hashMap.put("five", 5);
hashMap.put("six", 6);
hashMap.put("seven", 7);
hashMap.put("eight", 8);
hashMap.put("nine", 9);
StringBuilder result = new StringBuilder();
StringBuilder str = new StringBuilder();
// 입력 문자열을 한 글자씩 확인
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
// 숫자 문자는 그대로 결과 문자열에 추가
if(Character.isDigit(ch)){
result.append(ch);
} else {
// 숫자 단어를 완성하기 위해 문자 추가
str.append(ch);
// HashMap에 숫자 단어가 있는 경우 결과 문자열에 숫자로 추가
if(hashMap.containsKey(str.toString())){
result.append(hashMap.get(str.toString()));
str.setLength(0); // str 초기화
}
}
}
// 결과 문자열을 정수로 변환하여 반환
return Integer.parseInt(result.toString());
}
}
class Solution {
public int solution(String s) {
String[] strArr = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
for(int i = 0; i < strArr.length; i++) {
s = s.replaceAll(strArr[i], Integer.toString(i));
}
return Integer.parseInt(s);
}
}
String replaceAll(String regex, String replacement)
문자열에서 특정 패턴을 찾아 다른 문자열로 대체하는 기능 제공
String 클래스에 포함
-> 형변환 뿐만 뿐만 아니라 일치하는 모든 내용을 변경
public class ReplaceAllExample {
public static void main(String[] args) {
String s = "one two three";
String[] strArr = {"zero", "one", "two", "three", "four"};
for (int i = 0; i < strArr.length; i++) {
s = s.replaceAll(strArr[i], Integer.toString(i));
}
System.out.println(s); // "1 2 3"
}
}