zoukankan      html  css  js  c++  java
  • 【Leetcode】535. Encode and Decode TinyURL

    Question:

    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.

    Tips:

    将长的url转换为短url 将短url转换为长的url。长url与短url之间有一个映射,保证一致。
    如输入https://leetcode.com/problems/design-tinyurl 编码之后返回http://tinyurl.com/4e9iAk
    输入http://tinyurl.com/4e9iAk,decode之后也要返回https://leetcode.com/problems/design-tinyurl。

    编码方式没有限制,主要是code与decode之后 结果要相同。

    思路:

    code:

    输入类似:https://leetcode.com/problems/design-tinyurl

    用longUrl的哈希值作为hashmap的key,longUrl作为value,组成键值对,保存在map中。

    返回"http://tinyurl.com/"+longUrl的哈希值,即键值。

    decode:

    输入类似:http://tinyurl.com/4e9iAk

    根据http://tinyurl.com/ 后面的4e9iAk作为key 来查找对应的value就是longUrl

    代码:(使用hashmap)

    package medium;
    
    import java.util.HashMap;
    import java.util.Map;
    
    public class L535EncodeAndDecodeTinyURL {
        //即将长的url转换为短url 将短url转换为长的url。
        //长url与短url之间有一个映射,保证一致。
        //如输入https://leetcode.com/problems/design-tinyurl 编码之后返回http://tinyurl.com/4e9iAk
        //输入http://tinyurl.com/4e9iAk,decode之后也要返回https://leetcode.com/problems/design-tinyurl
        Map<Integer, String> map = new HashMap<>();
    
        // Encodes a URL to a shortened URL.
        public String encode(String longUrl) {
            map.put(longUrl.hashCode(), longUrl);
            //System.out.println("long hashCode"+longUrl.hashCode());
            return "http://tinyurl.com/" + longUrl.hashCode();
        }
    
        // Decodes a shortened URL to its original URL.
        public String decode(String shortUrl) {
            return map.get(Integer.parseInt(shortUrl.replace("http://tinyurl.com/", "")));
        }
    
        // Your Codec object will be instantiated and called as such:
        public static void main(String[] args) {
            L535EncodeAndDecodeTinyURL l535 = new L535EncodeAndDecodeTinyURL();
            System.out.println(l535.decode(l535.encode("https://leetcode.com/problems/design-tinyurl")));
        }
    }


       

  • 相关阅读:
    Qt 交叉编译经典错误——头文件包含
    Linux-Qt使用QThread多线程isRunning标志量问题
    个人总结——C、C++指针传参和初始化字符空间
    ARM板设置开机自启动应用程序
    python--ModuleFoundError
    php输出错误屏蔽的函数
    类QQ账号生成阐述
    Python基础(四)—日期类型
    Python基础(三)—字典和集合
    Python基础(二)—列表和元组
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/8583160.html
Copyright © 2011-2022 走看看