LeetCode Solutions

535. Encode and Decode TinyURL

Time:

Space:

			

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;
};
			

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();
}
			

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:]]