leetcode 535. Encode and Decode TinyURL(长短网址互译)

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.

说白了就是要你把长网址变成短网址,再将短网址转化成对应的长网址,而且方法不限,所以可以随意发挥,容易AC

这里长网址变成短网址采用的方法是,定义一个常量字符串0-9a-zA-Z,每次将长网址作为key存入Map时,在将对应的短网址(在那个字符串常量中随机挑去6个作为短网址)作为对应的value存入map中,在将两者对换,存入另一个map中,用于将短网址变成长网址。存入过程中会判断长网址是否出现过,以及随机生成的短网址是否出现过,在做相应处理。


代码如下

public class Codec {

    Map<String,String> longUrlToShortUrl = new HashMap<>();
	Map<String,String> shortUrlToLongUrl = new HashMap<>();

	private static final String code = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	
	// Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
    	
    	String encode=null;
    	if(longUrlToShortUrl.get(longUrl)!=null)
    	{
    		return longUrlToShortUrl.get(longUrl);
    	}
    	else
    	{
    		encode = Codec.encodeUrl();
    		while(shortUrlToLongUrl.get(encode)!=null)
    		{
    			encode = Codec.encodeUrl();
    		}
    		longUrlToShortUrl.put(longUrl,encode);
    		shortUrlToLongUrl.put(encode, longUrl);
    		return encode;	
    	}
    }

    public static String encodeUrl(){
    	String encode="";
		for(int i=0; i<6; i++)
		{
			String str = String.valueOf(code.charAt((int)(Math.random()*61)));
			encode = encode + str;
		}
		return encode;
    }
    
    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
    	String decode = shortUrlToLongUrl.get(shortUrl);
    	return decode == null ? "" : decode;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值