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的更多相关文章
随机推荐
- centos7 安装php 5.x.x 报错
错误1: /usr/src/php-5.2.9/ext/dom/node.c:In function 'dom_canonicalization': /usr/src/php-5.2.9/ext/do ...
- 用stack实现min stack
遇到个好玩的问题,就是用一个stack实现min stack,什么意思呢,就是我实现stack,但是能以O(1)的时间复杂度和空间复杂度去找到我stack里面的最小值. 常规的方法是:用一个变量存放当 ...
- HDU - 4336:Card Collector(min-max容斥求期望)
In your childhood, do you crazy for collecting the beautiful cards in the snacks? They said that, fo ...
- ss client 配置
1.1安装ss apt-get install python-pippip install shadowsocks 1.2配置ss 新建一个配置文件config.json/etc/shadowsock ...
- Luogu 1452 Beauty Contest
Luogu 1452 Beauty Contest 求平面最远点对,先求出凸包,再找凸包的直径. 使用旋转卡壳,直径一定出现在对踵点对间.比较不同点到同一直线距离可以用叉积算三角形面积来比较. 实现时 ...
- BZOJ4361 isn 【树状数组优化DP】*
BZOJ4361 isn Description 给出一个长度为n的序列A(A1,A2-AN).如果序列A不是非降的,你必须从中删去一个数,这一操作,直到A非降为止.求有多少种不同的操作方案,答案模1 ...
- select rows by values in a column from Dataframe
df.loc[df['column_name'] == some_value] details in: http://stackoverflow.com/questions/17071871/sele ...
- spring--注入方式
1.正常方式: 在一个“value”标签注入值,并附有“property”标签结束. <beans xmlns="http://www.springframework.org/sche ...
- ThinkPHP5 为什么取消了单字母函数?
ThinkPHP5 为什么取消了单字母函数? 更容易理解. 理加规范. 个人喜好. 比如 TPShop 也是用 ThinkPHP5 又加回单字母函数. [话唠]教练,我想做菜-长沙 2018/10/8 ...
- 搭建基于hyperledger fabric的联盟社区(九) --检索状态数据库
一.启动elasticsearch服务 官网下载压缩包解压,进入bin目录启动: ./elasticsearch 通过ip访问 localhost:9200,可以看到如下信息 { name: &quo ...