Golang | Leetcode Golang题解之第535题TinyURL的加密与解密
题目:
题解:
import "math/rand"
type Codec map[int]string
func Constructor() Codec {
return Codec{}
}
func (c Codec) encode(longUrl string) string {
for {
key := rand.Int()
if c[key] == "" {
c[key] = longUrl
return "http://tinyurl.com/" + strconv.Itoa(key)
}
}
}
func (c Codec) decode(shortUrl string) string {
i := strings.LastIndexByte(shortUrl, '/')
key, _ := strconv.Atoi(shortUrl[i+1:])
return c[key]
}