• [leetcode]535. Encode and Decode 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.

    题意:
    设计一个短网址的编解码器

    code

     1 public class Codec {
     2  
     3     private static final String SEED = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
     4     private static final String BASE = "http://tinyurl.com/";
     5 
     6     private static Map<String, String> keyToURL = new HashMap<>();
     7     private static Map<String, String> urlToKey = new HashMap<>();
     8 
     9     public static void main(String[] args) {
    10         String tinyURL = encode("http://thisislongurl.com/abcd/123");
    11         String longURL = decode(tinyURL);
    12 
    13         System.out.println("tinyURL = " + tinyURL);
    14         System.out.println("longURL = " + longURL);
    15     }
    16 
    17     public static String encode(String longUrl) {
    18         if (longUrl == null || longUrl.isEmpty()) {
    19             return null;
    20         }
    21         if (urlToKey.containsKey(longUrl)) {
    22             return BASE + urlToKey.get(longUrl);
    23         }
    24 
    25         StringBuilder key = null;
    26 
    27         // keep generating keys until a unique one is found
    28         do {
    29             key = new StringBuilder();
    30             for (int i = 0; i < 6; i++) {
    31                 int r = (int)(Math.random() * SEED.length());
    32                 key.append(SEED.charAt(r));
    33             }
    34         } while (keyToURL.containsKey(key));
    35 
    36         keyToURL.put(key.toString(), longUrl);
    37         urlToKey.put(longUrl, key.toString());
    38 
    39         return BASE + key;
    40     }
    41 
    42     public static String decode(String shortUrl) {
    43         if (shortUrl == null || shortUrl.isEmpty()) {
    44             return "";
    45         }
    46         String[] shortUrlSplits = shortUrl.split("/");
    47         return keyToURL.get(shortUrlSplits[shortUrlSplits.length - 1]);
    48     }
    49 }
  • 相关阅读:
    第三周作业
    面向过程(或者叫结构化)分析方法与面向对象分析方法到底区别在哪里?请根据自己的理解简明扼要的回答。
    移动APP开发使用什么样的原型设计工具比较合适?
    java 从上至下打印二叉树
    Qt applendPlainText()/append() 多添加一个换行解决方法
    tolua 转换 std::shared_ptr
    cmake add_custom_command 使用
    Boost使用笔记(Smart_ptr)
    webpack4 安装
    git安装管理
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10873338.html
Copyright © 2020-2023  润新知