-
Notifications
You must be signed in to change notification settings - Fork 112
/
0535-EncodeAndDecodeTinyURL.cs
51 lines (43 loc) · 1.48 KB
/
0535-EncodeAndDecodeTinyURL.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//-----------------------------------------------------------------------------
// Runtime: 88ms
// Memory Usage: 25.1 MB
// Link: https://leetcode.com/submissions/detail/262781663/
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace LeetCode
{
public class _0535_EncodeAndDecodeTinyURL
{
private const string ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private const string DOMAIN = "http://tinyurl.com/";
private readonly IDictionary<string, string> map = new Dictionary<string, string>();
private readonly Random random = new Random();
public string GetKey()
{
var sb = new StringBuilder();
for (int i = 0; i < 8; i++)
sb.Append(ALPHABET[random.Next(62)]);
return sb.ToString();
}
// Encodes a URL to a shortened URL
public string encode(string longUrl)
{
var key = string.Empty;
do
{
key = GetKey();
} while (map.ContainsKey(key));
map[key] = longUrl;
return DOMAIN + key;
}
// Decodes a shortened URL to its original URL.
public string decode(string shortUrl)
{
var key = shortUrl.Replace(DOMAIN, "");
map.TryGetValue(key, out var value);
return value;
}
}
}