zoukankan      html  css  js  c++  java
  • 0535. Encode and Decode TinyURL (M)

    Encode and Decode TinyURL (M)

    题目

    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.


    题意

    设计一个能将长URL和短URL互相转换的功能。

    思路

    无特定方法。


    代码实现

    Java

    public class Codec {
        private Map<String, String> toLong = new HashMap<>();
        private Map<String, String> toShort = new HashMap<>();
        private String pool = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        private Random random = new Random();
    
        // Encodes a URL to a shortened URL.
        public String encode(String longUrl) {
            String suffix = randomSuffix(5);
    
            if (toShort.containsKey(longUrl)) {
                suffix = toShort.get(longUrl);
            } else {
                while (suffix == null || toLong.containsKey(suffix)) {
                    suffix = randomSuffix(5);
                }
                toLong.put(suffix, longUrl);
                toShort.put(longUrl, suffix);
            }
            
            return "http://tinyurl.com/" + suffix;
        }
    
        // Decodes a shortened URL to its original URL.
        public String decode(String shortUrl) {
            return toLong.get(shortUrl.split("/", 4)[3]);
        }
    
        private String randomSuffix(int len) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < len; i++) {
                sb.append(pool.charAt(random.nextInt(62)));
            }
            return sb.toString();
        }
    }
    
  • 相关阅读:
    Codeforces Round #234A
    Java中的字符串
    Codeforces Round #376A (div2)
    node源码详解 (一)
    node源码详解(三)
    node源码详解(四)
    修改bootstrap modal模态框的宽度
    Bootstrap 模态框(Modal)插件
    JavaScript局部变量和全局变量的理解
    Javascript:谈谈JS的全局变量跟局部变量
  • 原文地址:https://www.cnblogs.com/mapoos/p/14538347.html
Copyright © 2011-2022 走看看