leetcode 535. Encode and Decode TinyURL(长短网址互译)
来源:互联网 发布:淘宝二次审核 编辑:程序博客网 时间:2024/06/05 16:55
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));
0 0
- leetcode 535. Encode and Decode TinyURL(长短网址互译)
- leetcode题解-535. Encode and Decode TinyURL
- 【LeetCode】535. Encode and Decode TinyURL
- LeetCode:535. Encode and Decode TinyURL
- Leetcode 535. Encode and Decode TinyURL
- leetcode 535. Encode and Decode TinyURL
- Leetcode 535. Encode and Decode TinyURL
- LeetCode 535. Encode and Decode TinyURL
- 【LeetCode】535. Encode and Decode TinyURL
- python--leetcode 535. Encode and Decode TinyURL
- leetcode 535. Encode and Decode TinyURL
- LeetCode-Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- 协议
- Poj-1731 Orders(生成可重集的排列)
- nyistoj_表达式求值
- @SuppressWarnings注解
- 不正经运维狗的文档13
- leetcode 535. Encode and Decode TinyURL(长短网址互译)
- jvm 老年代新生代
- 406. Queue Reconstruction by Height
- DNN-HMM 中 DNN 与 HMM 的关系
- MFC-两个基本控件:DateTimeControl以及CalendarControl
- Just a Hook 【线段树】-区间更改 求和
- 31. Next Permutation Medium
- 面象对象的三大特点
- Zookeeper 的安装