不好的方法:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20public class Codec {
List<String> urls = new ArrayList<>();
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
urls.add(longUrl);
return String.valueOf(urls.size() - 1);
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
int index = Integer.parseInt(shortUrl);
return urls.get(index);
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));
Good:1
2
3
4
5
6
7
8
9
10
11
12
13
14class Codec:
def __init__(self):
self.pool = itertools.permutations(string.printable, 6)
self.cache = {}
def encode(self, longUrl):
key = next(self.pool)
self.cache[key] = longUrl
return key
def decode(self, shortUrl):
key = shortUrl
return self.cache[key]