LeetCode 문제 풀이

[LeetCode] 535번 문제를 풀어보았다. (ft. java)

pantrom 2022. 4. 23. 10:35

2022년 04월 23일 토요일 - 토요일 넘 조아


오늘 올려볼 문제는 535번 Encode and Decode TinyURL 이라는 문제이다.


사진을 클릭하면 해당 문제로 이동합니다.

leetcode 문제 사진

오늘도 LeetCode 사이트 오늘의 문제를 가지고 왔다.

오늘 문제 신박했당


입력


입력을 설명하기 애매한 문제다. 문제를 참고하길 바란다.



풀이 및 코드


url을 압축하고 다시 압축해제하는 클래스를 구현하는 문제다.


오늘은 처음부터 정답을 생각해냈다.

해쉬맵 2개를 사용해서 문제를 풀었다.


이제 코드를 봐보자!


풀이코드

public class Codec {
    HashMap<Integer, String> encodeMap = new HashMap<>();
    HashMap<String, Integer> decodeMap = new HashMap<>();
    int index = 0;

    public String encode(String longUrl) {
        if(!decodeMap.containsKey(longUrl))
        {
            encodeMap.put(index, longUrl);
            decodeMap.put(longUrl, index++);
        }

        return "http://tinyurl.com/" + decodeMap.get(longUrl);
    }

    public String decode(String shortUrl) {
        int input = Integer.parseInt(shortUrl.substring(19));

        return encodeMap.get(input);
    }
}




제출 화면

leetcode 문제 맞았습니다


오늘 문제는 많이 신박해서 재밌었다.

내일 문제도 재밌었으면 좋겠다.


내일도 문제를 풀어서 블로그에 글을 쓸 수 있으면 좋겠다.