题目

Note: This is a companion problem to the System Design problem: Design TinyURL-System/).

TinyURL is a URL shortening service where you enter a URL such as [https://leetcode.com/problems/design-tinyurl](https://leetcode.com/problems/design-tinyurl) and it returns a short URL such as [http://tinyurl.com/4e9iAk](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.


题意

设计一个能将长URL和短URL互相转换的功能。

思路

无特定方法。


代码实现

Java

  1. public class Codec {
  2. private Map<String, String> toLong = new HashMap<>();
  3. private Map<String, String> toShort = new HashMap<>();
  4. private String pool = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  5. private Random random = new Random();
  6. // Encodes a URL to a shortened URL.
  7. public String encode(String longUrl) {
  8. String suffix = randomSuffix(5);
  9. if (toShort.containsKey(longUrl)) {
  10. suffix = toShort.get(longUrl);
  11. } else {
  12. while (suffix == null || toLong.containsKey(suffix)) {
  13. suffix = randomSuffix(5);
  14. }
  15. toLong.put(suffix, longUrl);
  16. toShort.put(longUrl, suffix);
  17. }
  18. return "http://tinyurl.com/" + suffix;
  19. }
  20. // Decodes a shortened URL to its original URL.
  21. public String decode(String shortUrl) {
  22. return toLong.get(shortUrl.split("/", 4)[3]);
  23. }
  24. private String randomSuffix(int len) {
  25. StringBuilder sb = new StringBuilder();
  26. for (int i = 0; i < len; i++) {
  27. sb.append(pool.charAt(random.nextInt(62)));
  28. }
  29. return sb.toString();
  30. }
  31. }