535. TinyURL 的加密与解密

TinyURL 的加密与解密

题目描述:

TinyURL是一种URL简化服务, 比如:当你输入一个URL https://leetcode.com/problems/design-tinyurl 时,它将返回一个简化的URL http://tinyurl.com/4e9iAk.

要求:设计一个 TinyURL 的加密 encode 和解密 decode 的方法。你的加密和解密算法如何设计和运作是没有限制的,你只需要保证一个URL可以被加密成一个TinyURL,并且这个TinyURL可以用解密方法恢复成原本的URL。

通过次数17,869提交次数21,114

思路:

时间复杂度:O(1),空间复杂度O(1)

用map,每次都给一个链接递增的数字就行

代码:

type Codec struct {
    m map[string]string
}


func Constructor() Codec {
    return Codec{m: map[string]string{}}
}

// Encodes a URL to a shortened URL.
func (this *Codec) encode(longUrl string) string {
    code:=strconv.Itoa(len(this.m)+1)
    this.m[code]=longUrl
    return code
}

// Decodes a shortened URL to its original URL.
func (this *Codec) decode(shortUrl string) string {
    return this.m[shortUrl]
}


/**
 * Your Codec object will be instantiated and called as such:
 * obj := Constructor();
 * url := obj.encode(longUrl);
 * ans := obj.decode(url);
 */

代码效率:

执行用时:0 ms, 在所有 Go 提交中击败了100.00%的用户
内存消耗:2.3 MB, 在所有 Go 提交中击败了82.50%的用户


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!