Leetcode 535. Encode and Decode TinyURL

257 篇文章 17 订阅

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, ""));
    }
}








  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值