爨爨爨好

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

▶ 要求给出一种对 URL 网址进行压缩和解压的算法,例如 https://leetcode.com/problems/design-tinyurl ←→ http://tinyurl.com/4e9iAk,在不允许打表的情况下应该无法压缩的。

● 代码,6 ms,完全不压缩,just for fun

1 class Solution
2 {
3 public:
4     // Encodes a URL to a shortened URL.
5     string encode(string longUrl) { return longUrl; }
6     // Decodes a shortened URL to its original URL.
7     string decode(string shortUrl) { return shortUrl; }
8 };
1 class Solution
2 {
3 public:
4     string theLatestUrl;
5     string encode(string longUrl) { theLatestUrl = longUrl; return "whatever, doesn't matter"; }
6     string decode(string shortUrl) { return theLatestUrl; }
7 };

● 代码,9 ms,随机数打表法,加密之后的字符串只与原网址字符串在表中的存放位置有关,与其内容无关。类似的有各种打表法,需要依赖散列表来解码,时间复杂度 O(1),空间开销大。

 1 class Solution
 2 {
 3 public:
 4     unordered_map<string, string> um;    
 5     string encode(string longUrl)
 6     {        
 7         const string baseUrl = "http://tinyurl.com/";
 8         int r;
 9         string ran;
10         srand(1); 
11         for (r = rand() % 100000, ran = to_string(r); um.count(baseUrl + ran) == 1; r = rand() % 100000, ran = to_string(r));
12             // 随机取一个空的位置把网址放进去
13         um[baseUrl + ran] = longUrl;
14         return baseUrl + ran;
15     }    
16     string decode(string shortUrl)
17     {
18         if (um.count(shortUrl) == 1)
19             return um[shortUrl];
20         return "";
21     }
22 };

 

posted on 2018-01-30 17:30  爨爨爨好  阅读(147)  评论(0编辑  收藏  举报