[C#][LeetCode][Easy] 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.
心得:

這題實務上的話我應該會用資料庫來存key,簡單易用不是嗎?
不過要小心的是不能使用流水號來當作tinyurl的參數,
這樣會有被猜出key的可能性,可能就隨機產生一個短的字串並檢查不能重複來當key

我的答案(轉base64):

1
2
3
4
5
6
7
8
9
10
11
12
13

public class Codec {

// Encodes a URL to a shortened URL
public string encode(string longUrl) {
return Convert.ToBase64String(Encoding.UTF8.GetBytes(longUrl));
}

// Decodes a shortened URL to its original URL.
public string decode(string shortUrl) {
return Encoding.UTF8.GetString(Convert.FromBase64String(shortUrl));
}
}

 

我的答案(guid):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

public class Codec {

private static Dictionary<string, string> dty = new Dictionary<string, string>();

// Encodes a URL to a shortened URL
public string encode(string longUrl) {
string guid = Guid.NewGuid().ToString();
dty.Add(guid, longUrl);
return guid;
}

// Decodes a shortened URL to its original URL.
public string decode(string shortUrl) {
string url = string.Empty;
return dty.TryGetValue(shortUrl, out url) ? url : null;
}
}