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));
  • 相关阅读:
    变色龙启动MAC时,错误信息“ntfs_fixup: magic doesn't match:”的解决办法
    显示/隐藏Mac隐藏文件
    Mac 输入法小技巧
    cocos2d popSceneWithTransition()方法
    Mac电脑怎么显示隐藏文件、xcode清除缓存
    Cocos2d-X研究之3.0 场景切换特效汇总
    DevExpresss LookUpEdit详解
    使用First查找集合报错:序列不包含任何匹配元素
    c# devExpress 如何让gridview既可以复制也可以双击跳转
    DevExpress GridView限制列只允许输入数字
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10212232.html
Copyright © 2011-2022 走看看