本文共 1949 字,大约阅读时间需要 6 分钟。
LeetCode刷题随记
LeetCode 第535题 解题思路
TinyURL is a URL shortening service where you enter a URL such as and it returns a short URL such as .
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.
题目一上来看懂了,但是属于完全没思路,因为没有一个object…很苦恼
思考了一会,然后百度了一下,发现最难的是保证短url的完全独立性,保证不出现重复长短对应。
保证一一对应最好的是使用Map<>,看了几种解法,最简单的应该是下面这种了。
解题思路
对于长url,从26个小写字母+10个数字+2大写字母取随机,长度固定为6。
每一次encode都要检查重复性即可。
代码
public class Codec { private static Maplongshort = new HashMap<>(); private static Map shortlong = new HashMap<>(); private static String HOST = "http://tinyurl.com/"; // Encodes a URL to a shortened URL. public String encode(String longUrl) { if(longshort.containsKey(longUrl)){ return HOST + longshort.get(longUrl); } String shortUrl; String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; do{ StringBuilder sb = new StringBuilder(); for(int i=0;i<6;i++){ int n = (int) (Math.random() * chars.length()); sb.append(chars.charAt(n)); } shortUrl = sb.toString(); }while(shortlong.containsKey(shortUrl)); shortlong.put(shortUrl,longUrl); longshort.put(longUrl,shortUrl); return HOST + shortUrl; } // Decodes a shortened URL to its original URL. public String decode(String shortUrl) { return shortlong.get(shortUrl.replace(HOST,"")); }}// Your Codec object will be instantiated and called as such:// Codec codec = new Codec();// codec.decode(codec.encode(url));
总结
相比较其他题,这个题的问题总感觉怪怪的。思路比较开放,看到有人用超级复杂的算法,但是能完全保证一致性(MD5),超级厉害,想比较而言,我就采用了比较简单的方法,还是借鉴了别人的思路。
还是要努力呀,争取刷完medium的难度,这样面试和笔试都能有点把握了。
转载地址:https://blog.csdn.net/weixin_43408733/article/details/89209347 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!