[์•Œ๊ณ ๋ฆฌ์ฆ˜]_[LeetCode]- 13. Roman to Integer

SAPCOยท2022๋…„ 7์›” 10์ผ
0

- [Algorithm]

๋ชฉ๋ก ๋ณด๊ธฐ
3/13
post-thumbnail

๐Ÿ“ 1. ๋ฌธ์ œ

LeetCode - Roman to Integer

๐Ÿ“ 2. ํ’€์ด

๐Ÿ“Œ 2-1. ์ตœ์ดˆ ํ’€์ด

(1) ๋ฐฉ๋ฒ•

  1. HashMap์— Key, value๋ฅผ ๊ฐ๊ฐ ์„ธํŒ…ํ•œ๋‹ค.
  2. String์˜ index๋ฅผ ์ˆœํšŒํ•œ๋‹ค.
    2-1. ์•ž์ž๋ฆฌ๊ฐ€ ๋’ท์ž๋ฆฌ๋ณด๋‹ค ์ž‘์„ ์‹œ ๊ฒฐ๊ณผ์—์„œ ์•ž์ž๋ฆฌ๋ฅผ ๋บ€๋‹ค.
    2-2. ๋’ท์ž๋ฆฌ๋ฅผ ๋”ํ•ด์ค€๋‹ค.

(2) ์ฝ”๋“œ

class Solution {
    public int romanToInt(String s) {
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        map.put('I', 1);
        map.put('V', 5);
        map.put('X', 10);
        map.put('L', 50);
        map.put('C', 100);
        map.put('D', 500);
        map.put('M', 1000);
        
        int result = 0;
        for(int i = 0; i < s.length()-1; i++) {
                if(map.get(s.charAt(i)) < map.get(s.charAt(i+1))) {
                    result -= map.get(s.charAt(i));
                }else {
                    result += map.get(s.charAt(i));
                }             
        }
        return result + map.get(s.charAt(s.length()-1));
    }
}

(3) ๊ฒฐ๊ณผ

๐Ÿ“ 3. ๊ฒฐ๋ก 

none

profile
SAP CO

0๊ฐœ์˜ ๋Œ“๊ธ€