LeetCode - Encode and Decode TinyURL
Posted IncredibleThings
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode - Encode and Decode TinyURL相关的知识,希望对你有一定的参考价值。
Note: This is a companion problem to the System Design problem: Design 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.
这里长网址变成短网址采用的方法是,定义一个常量字符串0-9a-zA-Z,每次将长网址作为key存入Map时,在将对应的短网址(在那个字符串常量中随机挑去6个作为短网址)作为对应的value存入map中,在将两者对换,存入另一个map中,用于将短网址变成长网址。存入过程中会判断长网址是否出现过,以及随机生成的短网址是否出现过,在做相应处理。
public class Codec { private static final String dict = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIKKLMNOPQRSTUVWXYZ"; Map<String,String> longToShort = new HashMap<>(); Map<String,String> shortToLong = new HashMap<>(); // Encodes a URL to a shortened URL. public String encode(String longUrl) { if(longToShort.containsKey(longUrl)){ return longToShort.get(longUrl); } String encoded = encodeString(); while(shortToLong.containsKey(encoded)){ encoded = encodeString(); } longToShort.put(longUrl, encoded); shortToLong.put(encoded, longUrl); return encoded; } public String encodeString(){ String res = ""; for(int i = 0; i<6; i++){ String str = String.valueOf(dict.charAt((int)(Math.random()*62))); res = res + str; } return res; } // Decodes a shortened URL to its original URL. public String decode(String shortUrl) { if(shortToLong.containsKey(shortUrl)){ return shortToLong.get(shortUrl); } return ""; } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.decode(codec.encode(url));
以上是关于LeetCode - Encode and Decode TinyURL的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 解题思路:535.Encode and Decode TinyURL
LeetCode - Encode and Decode TinyURL
Encode and Decode Strings -- LeetCode
leetcode535 - Encode and Decode TinyURL - medium