zoukankan      html  css  js  c++  java
  • [LC] 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.

    public class Codec {
        Map<String, String> map = new HashMap<>();
        String charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    
        // Encodes a URL to a shortened URL.
        public String encode(String longUrl) {
            Random rand = new Random();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 6; i++) {
                int index = rand.nextInt(charSet.length());
                sb.append(charSet.charAt(index));
            }
            String url = "http://tinyurl.com/" + sb.toString();
            if (!map.containsKey(url)) {
                map.put(url, longUrl);
            }
            return url;
        }
    
        // Decodes a shortened URL to its original URL.
        public String decode(String shortUrl) {
            return map.get(shortUrl);   
        }
    }
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec = new Codec();
    // codec.decode(codec.encode(url));
  • 相关阅读:
    [Usaco2008 Nov]mixup2 混乱的奶牛
    [Poi2004] 旅行问题
    [洛谷P1278]单词游戏
    redis20
    redis19
    redis18
    OHC Java堆外缓存详解与应用
    SQL优化
    Mysql安装、字符、引擎设置
    大文件下载
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12785612.html
Copyright © 2011-2022 走看看