LeetCode
LintCode 522 Tiny URLII - Medium
522. Tiny Url II
522. Tiny URLII — Medium
Problem
- Tiny Url II
As a follow up for Tiny URL, we are going to support custom tiny url, so that user can create their own tiny url. That is to say, you need to implement one more createCustom than 232. Tiny Url.
You should implement three methods:
longToShort(url) Convert a long url to a short url which starts with http://tiny.url/. shortToLong(url) Convert a short url to a long url. createCustom(url, key) Set the short url of a long url to http://tiny.url/ + key You can design any shorten algorithm, the judge only cares about:
The length of short key' generated by longToShort should equal to 6 (without domain and slash). And the acceptable characters are [a-zA-Z0-9]. For example: abcD9E No two long urls mapping to the same short url and no two short urls mapping to the same long url. If createCustom can not meet users' expectment, return "error"; otherwise return the short url. Example Example 1:
Input: createCustom("http://www.lintcode.com/", "lccode") shortToLong("http://tiny.url/lccode") createCustom("http://www.lintcode.com/", "ltcode") Output: "http://tiny.url/lccode" "http://www.lintcode.com/" "error" Example 2:
Input:
longToShort("http://www.lintcode.com/")
createCustom("http://www.lintcode.com/", "ltcode")
Output:
"http://tiny.url/abcdef" => This answer is not unique.
"error"
Explanation:
Although it is almost impossible:
if your longToShort() just returns "http://tiny.url/ltcode",
your createCustom() should return "http://tiny.url/ltcode".
Solution
import random
class TinyUrl2:
"""
@param: long_url: a long url
@param: key: a short key
@return: a short url starts with http://tiny.url/
"""
def __init__(self):
self.short2long = {}
self.long2short = {}
def createCustom(self, long_url, key):
# write your code here
short = "http://tiny.url/" + key
if short in self.short2long and self.short2long[short] != long_url:
return "error"
if long_url in self.long2short and self.long2short[long_url] != short:
return "error"
self.long2short[long_url] = short
self.short2long[short] = long_url
return short
"""
@param: long_url: a long url
@return: a short url starts with http://tiny.url/
"""
def longToShort(self, long_url):
# write your code here
if long_url in self.long2short:
return self.long2short[long_url]
short = self.generate_short()
while short in self.short2long:
short = self.generate_short()
self.short2long[short] = long_url
self.long2short[long_url] = short
return short
"""
@param: short_url: a short url starts with http://tiny.url/
@return: a long url
"""
def shortToLong(self, short_url):
# write your code here
if short_url not in self.short2long:
return "error"
return self.short2long[short_url]
def generate_short(self):
CHARS = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
LENS = 6
short = ""
for _ in range(LENS):
short += random.choice(CHARS)
return "http://tiny.url/" + short