535. Encode and Decode TinyURL
https://leetcode.com/problems/encode-and-decode-tinyurl/
Note: This is a companion problem to the System Design problem: Design TinyURL.
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl
and it returns a short URL such as http://tinyurl.com/4e9iAk
.
Design the encode
and decode
methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
---
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Codec { | |
Map<String, String> map = new HashMap<String, String>(); | |
Map<String, String> invMap = new HashMap<String, String>(); | |
String HOST ="http://tinyurl.com/"; | |
String keys = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; | |
// Encodes a URL to a shortened URL. | |
public String encode(String longUrl) { | |
if (map.containsKey(longUrl)) { | |
return map.get(longUrl); | |
} | |
String key = ""; | |
do { | |
StringBuilder sb = new StringBuilder(); | |
for (int i = 0; i < 6; i++) { | |
sb.append(keys.charAt((int)Math.random() * keys.length())); | |
} | |
key = sb.toString(); | |
} while (map.containsKey(key)); | |
key = HOST + key; | |
map.put(longUrl, key); | |
invMap.put(key, longUrl); | |
return key; | |
} | |
// Decodes a shortened URL to its original URL. | |
public String decode(String shortUrl) { | |
return invMap.get(shortUrl); | |
} | |
} | |
// Your Codec object will be instantiated and called as such: | |
// Codec codec = new Codec(); | |
// codec.decode(codec.encode(url)); |