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

    用两个hash map,分别表示long to short (map1) 和 short to long (map2) ,并把要用到的大小写字母和数字用string表示出来待用

    encode: 先check map1中是否有longURL, 如果存在直接返回对应的shortURL;如果没有,在string中随机选n个字符组合,并检查map2中是否存在该组合,如果存在再增加n个字符,直到该url组合是unique的。然后分别在map1, map2中都存入这对url pair

    decode: 直接返回map2中对应long url即可

    encode: time = O(n), space = O(n)  n: # of urls

    decode: time = O(1), space = O(1)

    public class Codec {
        Map<String, String> long2short = new HashMap<>();
        Map<String, String> short2long = new HashMap<>();    
        String ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        Random r = new Random();
    
        // Encodes a URL to a shortened URL.
        public String encode(String longUrl) {
            if(long2short.containsKey(longUrl)) {
                return "http://tinyurl.com/" + long2short.get(longUrl); 
            }
            StringBuilder sb = new StringBuilder();
            
            while(short2long.containsKey(sb.toString())) {
                for(int i = 0; i < 6; i++) {
                    sb.append(ch.charAt(r.nextInt(ch.length())));
                }
            }
            long2short.put(longUrl, sb.toString());
            short2long.put(sb.toString(), longUrl);
            return "http://tinyurl.com/" + sb.toString();
        }
    
        // Decodes a shortened URL to its original URL.
        public String decode(String shortUrl) {
            return short2long.get(shortUrl.substring("http://tinyurl.com/".length()));
        }
    }
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec = new Codec();
    // codec.decode(codec.encode(url));
  • 相关阅读:
    SQLServerframework启动报异常:Module的类型初始值设定项引发异常
    在coding或者github建立个人站点域名绑定
    Github速度慢的解决方法
    jsoup爬取网站图片
    activeMQ类别和流程
    Session session = connection.createSession(paramA,paramB);参数解析
    Ehcache入门经典:第二篇ehcache.xml的参数
    Ehcache入门经典:第一篇
    处理高并发
    扩充次数和创建个数问题
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10212232.html
Copyright © 2011-2022 走看看