[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.

方法

提供一个map和变量i,每来一个url的时候i++,将urli的对应关系存入map即可

python代码
class Codec:
    def __init__(self):
        self.map = {}
        self.i = 0
    
    def encode(self, longUrl):
        """Encodes a URL to a shortened URL.
        :type longUrl: str
        :rtype: str
        """
        self.i += 1
        self.map[self.i] = longUrl
        return "http://tinyurl.com/" + str(self.i)

    def decode(self, shortUrl):
        """Decodes a shortened URL to its original URL.
        :type shortUrl: str
        :rtype: str
        """
        return self.map[int(shortUrl.split('/')[-1])]

# Your Codes object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))

url = "https://leetcode.com/problems/design-tinyurl";
codec = Codec()
assert codec.decode(codec.encode(url)) == url
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,487评论 0 23
  • swift现在已经很普遍了,对于经常使用oc的同学来说cocospods很熟练了,一下是介绍swift中cocos...
    sttech阅读 2,823评论 0 0
  • 林森是比我高一级的学姐,人如其名,是一个小家碧玉的森女系美女。大一时我们相遇在文学社,从最开始的互相不来电到臭味相...
    echo敏阅读 5,344评论 21 34
  • 1 咱们先来思考三个问题: 做一件事情总是无法坚持 坏习惯总是很容易养成 坚持后的放纵 坏习惯往往很容易养成,而好...
    吏阳先生阅读 3,725评论 0 3
  • 我的舅舅死在我七岁那年,之所以记得是七岁,是因为那一年我上小学,从海岛村民变成了五线小城市的暂住居民,那里终于有肯...
    夏禾火阅读 2,241评论 2 3