0%

tiny_URL

Shorten URL

system design,很实用!

535. Encode and Decode TinyURL

如果想要实现相同的URL 加密成同一个 TinyURL,则额外保存一个从URLTinyURL 的映射。

法一:自增

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Codec {
Map<Integer,String> database=new HashMap<>();
int count=0;
String prefix="https://ivn.com/";
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
database.put(++count,longUrl);
return prefix+count;
}

// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
int p=shortUrl.lastIndexOf('/')+1;
int val=Integer.parseInt(shortUrl.substring(p));
return database.get(val);
}
}

法二:哈希生成

为了防止相同的 longUrl 多次调用,确保 encode 服务的「幂等性」,我们再额外建立哈希表 origin2Tiny 来记录原串和映射标识的对应关系。

法三:随机

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Codec {

Random random=new Random();
Map<Integer,String> database=new HashMap<>();
String prefix="https://ivn.com/";
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
int num= random.nextInt();
while(database.containsKey(num)){
num= random.nextInt();
}
database.put(num,longUrl);
return prefix+num;
}

// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
int p=shortUrl.lastIndexOf('/')+1;
int num=Integer.parseInt(shortUrl.substring(p));
return database.get(num);
}
}