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();
        }
    }
    
  • 相关阅读:
    SVM+HOG特征训练分类器
    数字图像处理的基本原理和常用方法
    c++中二进制和整数转化
    目标检测——HOG特征
    相似图片搜索的原理和实现——颜色分布法
    测试文本文件大小
    Direct2D 图形计算
    Direct2D 如何关闭抗锯齿
    MFC窗口显隐
    CISP/CISA 每日一题 22
  • 原文地址:https://www.cnblogs.com/mapoos/p/14538347.html
Copyright © 2011-2022 走看看