public class Codec
{
const string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; Dictionary<string, string> url2code = new Dictionary<string, string>();
Dictionary<string, string> code2url = new Dictionary<string, string>(); const string TINYURL = "http://tinyurl.com/"; // Encodes a URL to a shortened URL
public string encode(string longUrl)
{
while (!url2code.ContainsKey(longUrl))//原来没有这个url的short版本
{
//需要生成一个新的
var random = new Random(DateTime.Now.Millisecond);
StringBuilder sb = new StringBuilder();
while (sb.Length < )
{
var index = random.Next();
sb.Append(alphabet[index]);
}
var code = TINYURL + sb.ToString();
if (!code2url.ContainsKey(code))//新生成的这个code,之前没用过
{
url2code.Add(longUrl, code);
code2url.Add(code, longUrl);
}
}
return url2code[longUrl];
} // Decodes a shortened URL to its original URL.
public string decode(string shortUrl)
{
if (code2url.ContainsKey(shortUrl))
{
return code2url[shortUrl];
}
else
{
return shortUrl;
}
}
} // Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));

https://leetcode.com/problems/encode-and-decode-tinyurl/#/description

leetcode535的更多相关文章

随机推荐

  1. Git详解之四 服务器上的Git

    以下内容转载自:http://www.open-open.com/lib/view/open1328069988843.html 服务器上的 Git 到目前为止,你应该已经学会了使用 Git 来完成日 ...

  2. Linux 中断处理

    HardIRQ 和 softirq : http://www.it165.net/os/html/201211/3766.html 博文:http://blog.csdn.net/yin262/art ...

  3. BZOJ1096 ZJOI2007 仓库建设 【斜率优化DP】

    BZOJ1096 ZJOI2007 仓库建设 Description L公司有N个工厂,由高到底分布在一座山上.如图所示,工厂1在山顶,工厂N在山脚.由于这座山处于高原内陆地区(干燥少雨),L公司一般 ...

  4. ORACLE PL/SQL:触发器

    ORACLE PL/SQL 触发器 本篇主要内容如下: 8.1 触发器类型 8.1.1 DML触发器 8.1.2 替代触发器 8.1.3 系统触发器 8.2 创建触发器 8.2.1 触发器触发次序 8 ...

  5. 《selenium2 python 自动化测试实战》(7)——定位一组对象

    定位一组对象 定位一组对象——find_elements_by_...(),注意,这里是elements,复数.返回的结果是一个列表,我们取值的时候就要用列表取值的方式来获得自己想要的元素.需要注意的 ...

  6. Web应用程序开发知识点回顾

    asp.net 1.<%@ Page Language="C#"AutoEventWireup="true" CodeFile="Home.as ...

  7. ckeditor使用教程

    ckeditor 的官方网站是 http://ckeditor.com/ 一.使用方法: 1.在页面<head>中引入ckeditor核心文件ckeditor.js <script ...

  8. Python基础之路

    一.Python基础之简介 二.Python基础之数据类型 三.Python之运算符 三.Python变量 四.Python之流程控制 三.Python基础之函数 四.Python基础之面向对象

  9. rundll32命令大全

    rundll32命令大全 命令列:rundll32.exe user.exe,restartwindows 功能: 系统重启 命令列:rundll32.exe user.exe,exitwindows ...

  10. c#代码加密

    源代码保护:怎样利用MaxtoCode加密dotNet源代码 http://www.webkaka.com/blog/archives/MaxtoCode-encrypt-dotnet-program ...