• [leetcode-535-Encode and Decode TinyURL]


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

    思路:
    encode : 将网址映射到一个id上,使用hash map,保存对应的id和网址。

    decode:用短网址计算出id,然后返回对应的长网址。

    string dict = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
         int id = 0;
         unordered_map<string, string>m;
         unordered_map<int, string>idm;
         // Encodes a URL to a shortened URL.
         string encode(string longUrl)
         {
             if (m.find(longUrl) != m.end())return m[longUrl];
             string res = "";
             id++;
             int count = id;
             while (count > 0)
             {
                 res = dict[count % 62] + res;
                 count /= 62;
             }
             while (res.size() < 6) res = "0" + res;
             m[longUrl] = res;
             idm[id] = longUrl;
             return res;
         }
         // Decodes a shortened URL to its original URL.
         string decode(string shortUrl)
         {
             int id = 0;
             for (int i = 0; i < shortUrl.size();i++)
             {
                 id = 62 * id + (int)(dict.find(shortUrl[i]));
             }
             if (idm.find(id) != idm.end())return idm[id];
             return "";
         }

    参考:

    https://discuss.leetcode.com/topic/81588/c-solution

  • 相关阅读:
    html5 语义
    HTML Web Workers
    创建删除元素appendChild,removeChild,createElement,insertBefore
    getPos封装
    getPos,offsetTop
    HTML 中有用的字符实体
    ellipsis
    HTML 统一资源定位器
    width,clientWidth,offsetWidth
    .offsetLeft,.offsetTop
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6873176.html
Copyright © 2020-2023  润新知