Leetcode 535. Encode and Decode TinyURL
The “Encode and Decode TinyURL” problem is all about designing a system for encoding and decoding URLs, similar to the services provided by TinyURL. Specifically, you’ll need to implement two methods:
String encode(String longUrl)
: This method takes a long URL and returns a tiny URL.String decode(String shortUrl)
: This method takes a tiny URL and returns the original long URL.The key challenges here are to ensure that:
longToShort
: maps long URLs to their short form.shortToLong
: maps short URLs back to their original long form.shortToLong
map to retrieve the original URL.import java.util.HashMap;
import java.util.Random;
public class Codec {
private HashMap<String, String> longToShort;
private HashMap<String, String> shortToLong;
private static final String CHAR_SET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String BASE_URL = "http://tinyurl.com/";
private static final int KEY_LENGTH = 6;
private Random rand;
public Codec() {
longToShort = new HashMap<>();
shortToLong = new HashMap<>();
rand = new Random();
}
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
if (longToShort.containsKey(longUrl)) {
return longToShort.get(longUrl);
}
String shortUrl = "";
do {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < KEY_LENGTH; i++) {
sb.append(CHAR_SET.charAt(rand.nextInt(CHAR_SET.length())));
}
shortUrl = BASE_URL + sb.toString();
} while (shortToLong.containsKey(shortUrl));
longToShort.put(longUrl, shortUrl);
shortToLong.put(shortUrl, longUrl);
return shortUrl;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return shortToLong.get(shortUrl);
}
}
This solution ensures efficient encoding and decoding operations even with a considerable volume of URLs.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?