-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution535.go
More file actions
42 lines (34 loc) · 884 Bytes
/
solution535.go
File metadata and controls
42 lines (34 loc) · 884 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package solution535
// ============================================================================
// 535. Encode and Decode TinyURL
// URL: https://leetcode.com/problems/encode-and-decode-tinyurl/
// ============================================================================
import (
"crypto/sha1"
"encoding/hex"
)
type Codec struct {
urls map[string]string
}
func Constructor() Codec {
return Codec{
urls: make(map[string]string),
}
}
// Encodes a URL to a shortened URL.
func (c *Codec) encode(longUrl string) string {
h := sha1.New()
h.Write([]byte(longUrl))
hash := hex.EncodeToString(h.Sum(nil))
shortUrl := "http://tinyurl.com/" + string(hash)
c.urls[shortUrl] = longUrl
return shortUrl
}
// Decodes a shortened URL to its original URL.
func (c *Codec) decode(shortUrl string) string {
url, ok := c.urls[shortUrl]
if ok {
return url
}
return ""
}