Skip to content

Latest commit

 

History

History
97 lines (75 loc) · 2.04 KB

File metadata and controls

97 lines (75 loc) · 2.04 KB

535. Encode and Decode TinyURL

Leetcode link

解题思路

这道题让我们模拟短链接生成算法。这题出的……直接原路返回也能过。

一般而言,短链接生成分为两步:

  1. 根据某种规则生成后面的乱序字符串
  2. 将乱序字符串与原来的长链接建立映射关系

C++

class Solution {
 private:
  unordered_map<string, string> urlMap;
  string characters =
      "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

 public:
  // Encodes a URL to a shortened URL.
  string encode(string longUrl) {
    srand(time(NULL));
    // 因为测试用例规模就 700 多个,用 4 位字符串已经够了
    string tinyUrl = "http://tinyurl.com/" + generateRandomStr(4);
    urlMap[tinyUrl] = longUrl;
    return tinyUrl;
  }

  // Decodes a shortened URL to its original URL.
  string decode(string shortUrl) { return urlMap[shortUrl]; }

  string generateRandomStr(int length) {
    string res = "";
    while (length--) {
      int randomIndex = rand() % 62;
      res += characters[randomIndex];
    }
    return res;
  }
};

Javascript

/**
 * Encodes a URL to a shortened URL.
 *
 * @param {string} longUrl
 * @return {string}
 */
var encode = function(longUrl) {
  // 因为测试用例规模就 700 多个,用 4 位字符串已经够了
    let tinyUrl = "http://tinyurl.com/" + generateRandomStr(4);
    urlMap[tinyUrl] = longUrl;
    return tinyUrl;
};

/**
 * Decodes a shortened URL to its original URL.
 *
 * @param {string} shortUrl
 * @return {string}
 */
var decode = function(shortUrl) {
    return urlMap[shortUrl];
};

var urlMap = {};
const characters =
      "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

var generateRandomStr = function(length) {
    let res = ''
    while (length--) {
      let randomIndex = Math.random() % 62;
      res += characters[randomIndex];
    }
    return res;
}

/**
 * Your functions will be called as such:
 * decode(encode(url));
 */