leetcode535
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的更多相关文章
随机推荐
- pip 在windows下的更新升级
1. pip 在 PyCharm 无法自动更新 2. https://pip.pypa.io/en/latest/installing.html 官方网页要求在 cmd中输入以下命令进行 pip的 ...
- mysql拼接多条查询结果并且加序列
SELECT GROUP_CONCAT(a.DESCRIPTION SEPARATOR '\n') FROM (SELECT (@rowNum:=0) AS rowNo,CONCAT('公司内 ...
- ORACLE PL/SQL:触发器
ORACLE PL/SQL 触发器 本篇主要内容如下: 8.1 触发器类型 8.1.1 DML触发器 8.1.2 替代触发器 8.1.3 系统触发器 8.2 创建触发器 8.2.1 触发器触发次序 8 ...
- python模块--随机模块
import random print(random.random()) # 随机产生一个(0,1)的 float 0.026244299361600776 print(random.randint( ...
- struts 2整合spring要注意的问题(二)
在 struts2_spring_plugin.xml配置文件里有一个strus.objectFactory.spring.autoWire 属性 默认值为name 也就是说你不想装载.它都会找个 ...
- [LeetCode系列]链表环探测问题II
给定一个链表头, 探测其是否有环, 如果没有返回NULL, 如果有返回环开始的位置. 环开始的位置定义为被两个指针指向的位置. 算法描述: 1. 快慢指针遍历, 如果到头说明无环返回NULL, 如果相 ...
- c/c++程序设计涉及的一些知识点
c/c++程序设计涉及的一些知识点 c中的printf函数 main(){ int b = 3; int arr[]= {6,7,8,9,10}; int * ptr = arr; *(ptr++) ...
- WebApi全局异常处理方式
自定义错误消息 public class ErrorMessage:DelegatingHandler { protected override Task<HttpResponseMessage ...
- Ubuntu secuerCRT连接失败,The remote system refused the connection.
新安装的ubuntu系统,securtCRT连接失败,出现下面结果,这是因为ubuntu没有安装工具. The remote system refused the connection. 解决办法: ...
- matlab读写图片,读取图像序列,读取AVI视频
介绍使用matlab读写图片,读取图像序列,读取AVI视频的方法: 一.读写图像 使用matlab读一幅图像,并另存 % Filename: ImageReadWrite clc; clear; i ...