您的位置:首页 > 其它

Leetcode 535. Encode and Decode TinyURL

2017-04-25 00:53 495 查看
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.
这个简单,设置一个从0开始的数字(类似于数据库中的key),然后一一映射到这些长url中就好了,再把数字作为短url。代码如下:

public class Encode_and_Decode_TinyURL_535 {
ArrayList<String> urLs=new ArrayList<String>();

// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
int index=urLs.size();
urLs.add(longUrl);
return String.valueOf(index);
}

// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
int index=Integer.parseInt(shortUrl);
return urLs.get(index);
}
}


但是leetcode上的牛人提出了几点问题:

如果我多次将同一个长url来进行编码,那么我会得到好几个短url,这浪费了存储空间。
会将多少个url已被编码暴露在阳光下,有些人也许会为了得到特殊的数字故意多次输入相同的长url。
只使用数字意味着短url也许会变得特别长。长度为6(100000)也只能获得百万级别的编码数。如果采取数字或大小写字母组合的6个字符的话,能提供(10+26*2)*6=56,800,235,584 个编码,比百万级可观多了!

下面的解题思路不再是只用字母,而是保证短url长度为6,但是里面可以包含数字或大小写字母。比如http://tinyurl.com/KtLa2U这种格式(貌似新浪微博就是这样转换长url的?)当一个长url已经被转化成短url了,将会直接提取之前转化成的短url,保证存储空间不被浪费。

public class Codec {
Map<String, String> index = new HashMap<String, String>();
Map<String, String> revIndex = new HashMap<String, String>();
static String BASE_HOST = "http://tinyurl.com/";

// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
if (revIndex.containsKey(longUrl)) return BASE_HOST + revIndex.get(longUrl);
String charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
String key = null;
do {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 6; i++) {
int r = (int) (Math.random() * charSet.length());
sb.append(charSet.charAt(r));
}
key = sb.toString();
} while (index.containsKey(key));
index.put(key, longUrl);
revIndex.put(longUrl, key);
return BASE_HOST + key;
}

// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return index.get(shortUrl.replace(BASE_HOST, ""));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: