码迷,mamicode.com
首页 > Web开发 > 详细

[LeetCode] Encode and Decode TinyURL

时间:2017-07-09 14:42:59      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:tiny   problems   where   algorithm   shorturl   ret   cal   its   ant   

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: 将longUrl压入栈中,并将longUrl后缀转换为数字加入到tinyurl的后缀。

decode: 找出tinyurl的后缀数字,返回栈中数字对应的longUrl.

class Solution {
public:
    vector<string> urls;
    // Encodes a URL to a shortened URL.
    string encode(string longUrl) {
        urls.push_back(longUrl);
        return "http://tinyurl.com/" + to_string(urls.size() - 1);
    }

    // Decodes a shortened URL to its original URL.
    string decode(string shortUrl) {
        auto pos = shortUrl.find_last_of(/);
        int num = stoi(shortUrl.substr(pos + 1));
        return urls[num];
    }
};
// 3ms

// Your Solution object will be instantiated and called as such:
// Solution solution;
// solution.decode(solution.encode(url));

 

[LeetCode] Encode and Decode TinyURL

标签:tiny   problems   where   algorithm   shorturl   ret   cal   its   ant   

原文地址:http://www.cnblogs.com/immjc/p/7141326.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!