-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path535.encode-and-decode-tinyurl.py
67 lines (62 loc) · 1.81 KB
/
535.encode-and-decode-tinyurl.py
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#
# @lc app=leetcode id=535 lang=python
#
# [535] Encode and Decode TinyURL
#
# https://leetcode.com/problems/encode-and-decode-tinyurl/description/
#
# algorithms
# Medium (77.11%)
# Total Accepted: 78.3K
# Total Submissions: 101.5K
# Testcase Example: '"https://leetcode.com/problems/design-tinyurl"'
#
# Note: This is a companion problem to the System Design problem: Design
# 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.
#
#
class Codec:
dic = dict()
alpha = string.ascii_letters + '0123456789'
def calc(self, s):
e = 7
val = 0
for i,c in enumerate(s):
val += e*ord(c)
e+=1
val = val%62
return self.alpha[val]
def encc(self, s):
ret = ""
for x in s.split('/'):
if len(x)==0:
continue
ret += self.calc(x)
return ret
def encode(self, longUrl):
"""Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str
"""
en = self.encc(longUrl)
# print(en)
self.dic[en] = longUrl
return "http://tinyurl.com/" + en
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL.
:type shortUrl: str
:rtype: str
"""
return self.dic[shortUrl[19:]]
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))