我们就爱程序媛

535. Encode and Decode TinyURL

2017-09-05  本文已影响0人  Nautilus1

题目描述:给一个长的URL地址,设计encode 和 decode函数把它缩短,使得缩短前后的地址一一对应。即如下代码可以返回原串:

codec = Codec()
codec.decode(codec.encode(url))

分析:题目并没有指定用什么对应方法,只要通过原URL能找到对应缩短的URL,通过缩短的URL可以返回原URL即可。

方法一:在两个函数中并不做处理,直接返回传来的参数串。偷懒的方法,严格说不符合题目要求,但复杂度肯定最低。代码:

class Codec:
    def encode(self, longUrl):
        """Encodes a URL to a shortened URL.
        :type longUrl: str
        :rtype: str
        """
        return longUrl

    def decode(self, shortUrl):
        """Decodes a shortened URL to its original URL.
        :type shortUrl: str
        :rtype: str
        """
        return shortUrl

方法二:取URL的第一个‘/’以前的部分,再加上此串在输入中的序号。首先给类添加初始化函数,里面声明一个列表存储输入的URL序列,处理过程需要调用一些内置函数。代码:

class Codec:
    def __init__(self):
        self.urls = []

    def encode(self, longUrl):
        """Encodes a URL to a shortened URL.
        :type longUrl: str
        :rtype: str
        """
        self.urls.append(longUrl)
        #从0开始
        return 'http://tinyurl.com/' + str(len(self.urls) - 1)   

    def decode(self, shortUrl):
        """Decodes a shortened URL to its original URL.
        :type shortUrl: str
        :rtype: str
        """
        #先获取该shortUrl的序号
        return self.urls[int(shortUrl.split('/')[-1])]
上一篇下一篇

猜你喜欢

热点阅读