← Static tasks

535. Encode and Decode TinyURL

leetcode medium

#csharp#design#hash-table#leetcode#medium#prefix-sum#search#string

Task

Спроектируйте класс для кодирования URL и декодирования короткого URL.

C# solution

matched/original
public class Codec {
    private static string alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private Dictionary<string, string> map = new Dictionary<string, string>();
    private Random rand = new Random();
    
    private string GetRand() {
        var sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            sb.Append(alphabet[rand.Next(62)]);
        }
        return sb.ToString();
    }
    public string Encode(string longUrl) {
        string key = GetRand();
        while (map.ContainsKey(key)) {
            key = GetRand();
        }
        map[key] = longUrl;
        return "http://tinyurl.com/" + key;
    }
    public string Decode(string shortUrl) {
        string key = shortUrl.Replace("http://tinyurl.com/", "");
        return map[key];
    }
}

C++ solution

auto-draft, review before submit
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
public class Codec {
    private static string alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private unordered_map<string, string> map = new unordered_map<string, string>();
    private Random rand = new Random();
    
    private string GetRand() {
        var sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            sb.Append(alphabet[rand.Next(62)]);
        }
        return sb.ToString();
    }
    public string Encode(string longUrl) {
        string key = GetRand();
        while (map.count(key)) {
            key = GetRand();
        }
        map[key] = longUrl;
        return "http://tinyurl.com/" + key;
    }
    public string Decode(string shortUrl) {
        string key = shortUrl.Replace("http://tinyurl.com/", "");
        return map[key];
    }
}

Java solution

matched/original
public class Codec {
    String alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    HashMap<String, String> map = new HashMap<>();
    Random rand = new Random();
    String key = getRand();

    public String getRand() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            sb.append(alphabet.charAt(rand.nextInt(62)));
        }
        return sb.toString();
    }

    public String encode(String longUrl) {
        while (map.containsKey(key)) {
            key = getRand();
        }
        map.put(key, longUrl);
        return "http://tinyurl.com/" + key;
    }

    public String decode(String shortUrl) {
        return map.get(shortUrl.replace("http://tinyurl.com/", ""));
    }
}

JavaScript solution

matched/original
class Codec {
    constructor() {
        this.alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        this.map = new Map();
    }
    
    getRand() {
        let result = '';
        for (let i = 0; i < 6; i++) {
            result += this.alphabet[Math.floor(Math.random() * 62)];
        }
        return result;
    }

    encode(longUrl) {
        let key = this.getRand();
        while (this.map.has(key)) {
            key = this.getRand();
        }
        this.map.set(key, longUrl);
        return 'http://tinyurl.com/' + key;
    }

    decode(shortUrl) {
        const key = shortUrl.replace('http://tinyurl.com/', '');
        return this.map.get(key);
    }
}

Python solution

matched/original
import random
import string

class Codec:
    def __init__(self):
        self.alphabet = string.ascii_letters + string.digits
        self.map = {}
        self.key = self.get_rand()

    def get_rand(self):
        return ''.join(random.choice(self.alphabet) for _ in range(6))

    def encode(self, longUrl: str) -> str:
        while self.key in self.map:
            self.key = self.get_rand()
        self.map[self.key] = longUrl
        return "http://tinyurl.com/" + self.key

    def decode(self, shortUrl: str) -> str:
        key = shortUrl.replace("http://tinyurl.com/", "")
        return self.map.get(key, "")

Go solution

matched/original
package main

import (
    "math/rand"
    "time"
)

type Codec struct {
    alphabet string
    map      map[string]string
}

func Constructor() Codec {
    rand.Seed(time.Now().UnixNano())
    return Codec{
        alphabet: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
        map:      make(map[string]string),
    }
}

func (this *Codec) getRand() string {
    result := make([]byte, 6)
    for i := 0; i < 6; i++ {
        result[i] = this.alphabet[rand.Intn(62)]
    }
    return string(result)
}

func (this *Codec) Encode(longUrl string) string {
    key := this.getRand()
    for _, exists := this.map[key]; exists; {
        key = this.getRand()
    }
    this.map[key] = longUrl
    return "http://tinyurl.com/" + key
}

func (this *Codec) Decode(shortUrl string) string {
    key := shortUrl[19:]
    return this.map[key]
}

Explanation

Algorithm

Реализуйте класс Solution:

Solution() Инициализирует объект системы.

String encode(String longUrl) Возвращает короткий URL для данного longUrl.

String decode(String shortUrl) Возвращает исходный длинный URL для данного shortUrl. Гарантируется, что данный shortUrl был закодирован тем же объектом.

Пример:

Input: url = "https://leetcode.com/problems/design-tinyurl"

Output: "https://leetcode.com/problems/design-tinyurl"

Explanation:

Solution obj = new Solution();

string tiny = obj.encode(url); // returns the encoded tiny url.

string ans = obj.decode(tiny); // returns the original url after decoding it.

👨‍💻

Алгоритм:

Инициализация:

Создайте строку, содержащую все возможные символы (цифры и буквы), которые могут быть использованы для генерации кода.

Создайте хэш-таблицу для хранения соответствий коротких и длинных URL-адресов.

Создайте объект для генерации случайных чисел.

Кодирование:

Сгенерируйте случайный 6-символьный код.

Если такой код уже существует в хэш-таблице, повторите генерацию.

Сохраните соответствие длинного URL и сгенерированного кода в хэш-таблице.

Верните полный короткий URL.

Декодирование:

Удалите префикс короткого URL, чтобы получить код.

Используйте код для поиска длинного URL в хэш-таблице.

Верните длинный URL.

😎