Skip to content

535. Encode and Decode TinyURL 👎

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
 public:
  string encode(string longUrl) {
    while (!urlToCode.count(longUrl)) {
      string code;
      for (int i = 0; i < 6; ++i)
        code += alphabets[rand() % alphabets.size()];
      if (!codeToUrl.count(code)) {
        codeToUrl[code] = longUrl;
        urlToCode[longUrl] = code;
        return "http://tinyurl.com/" + code;
      }
    }

    throw;
  }

  string decode(string shortUrl) {
    return codeToUrl[shortUrl.substr(19)];
  }

 private:
  const string alphabets =
      "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  unordered_map<string, string> urlToCode;
  unordered_map<string, string> codeToUrl;
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Codec {
  public String encode(String longUrl) {
    while (!urlToCode.containsKey(longUrl)) {
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < 6; ++i) {
        final char nextChar = alphabets.charAt(rand.nextInt(alphabets.length()));
        sb.append(nextChar);
      }
      final String code = sb.toString();
      if (!codeToUrl.containsKey(code)) {
        codeToUrl.put(code, longUrl);
        urlToCode.put(longUrl, code);
        return "http://tinyurl.com/" + code;
      }
    }

    throw new IllegalArgumentException();
  }

  public String decode(String shortUrl) {
    return codeToUrl.get(shortUrl.substring(19));
  }

  private static final String alphabets =
      "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  private Map<String, String> urlToCode = new HashMap<>();
  private Map<String, String> codeToUrl = new HashMap<>();
  private Random rand = new Random();
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Codec:
  alphabets = string.ascii_letters + '0123456789'
  urlToCode = {}
  codeToUrl = {}

  def encode(self, longUrl: str) -> str:
    while longUrl not in self.urlToCode:
      code = ''.join(random.choice(self.alphabets) for _ in range(6))
      if code not in self.codeToUrl:
        self.codeToUrl[code] = longUrl
        self.urlToCode[longUrl] = code
    return 'http://tinyurl.com/' + self.urlToCode[longUrl]

  def decode(self, shortUrl: str) -> str:
    return self.codeToUrl[shortUrl[-6:]]