[레벨1] 숫자 문자열과 영단어 (JAVA)

Fekim·2022년 3월 14일
0

ps

목록 보기
40/48
  • String 클래스의 substring 메소드를 활용해 문제를 해결하였다.
  • 정수를 만나거나, one two three... 의 문자열을 만나면 그 문자열을 제외한 다음 문자열부터 다시 루프를 시작하도록 구현했다.
import java.util.*;

class Solution {
    public int solution(String s) {
        int answer = 0;
        StringBuilder sb = new StringBuilder();
        HashMap<String, Integer> map = new HashMap<>();
        map.put("zero",0);
        map.put("one", 1);
        map.put("two", 2);
        map.put("three", 3);
        map.put("four", 4);
        map.put("five", 5);
        map.put("six", 6);
        map.put("seven", 7);
        map.put("eight", 8);
        map.put("nine", 9);
        
        String temp = "";
        
        int i=0;
        while(s.length()>0){
        	// 맨 앞 글자가 정수
            if(Character.isDigit(s.charAt(i))){
                sb.append(s.charAt(i));
                s = s.substring(i+1);
                i = 0;
            } else {	// 맨 앞글자가 문자
                temp += s.charAt(i);	// 문자를 누적
                
                if(map.containsKey(temp)){		// 누적된 문자가 map에 있다면
                    sb.append(map.get(temp));	// 결과에 반영하고, substring으로 자른다.
                    s = s.substring(i+1);
                    temp = "";
                    i = 0;
                }
                else	// 정수도 아니고, one two 같은 문자도 아닐시 index 증가.
                    i++;
            }
        }
        
        answer = Integer.parseInt(sb.toString());
        return answer;
    }
}
profile
★Bugless 2024★

0개의 댓글