TinyURL记录

本文介绍了在网易游戏面试中遇到的TinyURL系统设计问题。面试官询问如何使用短网址映射长网址,作者最初认为这种方法不足以应对大量长网址,但后来了解到可以采用base62编码,利用62种字符组合生成26^6种可能性,足以满足需求。此外,提到了LeetCode上的相关编码解码题目,并给出了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前去网易游戏面试,结果凉了。

当时面试官问了我一个问题:如何实现一个短网址(Tiny url)系统。当时我只说是建立一个映射,就跟哈希表的原理差不多。然后面试官问我用较短的网址去映射那么多的较长的网址,短网址够用吗?我当时理所当然地觉得:不够用,很快就否认了自己先前的想法。然后就慌了,接下来基本上啥也没说上来。。。


后来上网查这个问题的做法,发现LeetCode就有= =,而且其实思路大体也没错。

这是一种被称为base62的做法。只用6位的大小写字母加数字的组合来构造短网址,就可以有62^6(26个小写字母+26个大写字母+10个数字)种可能。这样就已经达到了五百亿的数量级,其实基本能够满足正常的短网址服务。


535Encode 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.


这是我的AC代码:


class Solution {
public:
    unordered_map<string, int> ltos;
    unordered_map<int, string> stol;
    int COUNTER = 1;
    string elements = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    int base62ToBase10(string s) {
        int n = 0;
        for (int i = 0; i < s.length(); i++) {
            n = n * 62 + convert(s[i]);
        }
        return n;
        
    }
    int convert(char c) {
        if (c >= '0' && c <= '9')
            return c - '0';
        if (c >= 'a' && c <= 'z') {
            return c - 'a' + 10;
        }
        if (c >= 'A' && c <= 'Z') {
            return c - 'A' + 36;
        }
        return -1;
    }
    string base10ToBase62(int n) {
        string sb = "";
        while (n != 0) {
            sb=elements[n % 62]+sb;
            n /= 62;
        }
        while (sb.length() != 6) {
            sb='0'+sb;;
        }
        return sb;
    }
    
    // Encodes a URL to a shortened URL.
    string encode(string longUrl) {
        string shorturl = base10ToBase62(COUNTER);
        ltos[longUrl]=COUNTER;
        stol[COUNTER]=longUrl;
        COUNTER++;
        return "http://tiny.url/" + shorturl;
    }

    // Decodes a shortened URL to its original URL.
    string decode(string shortUrl) {
        shortUrl = shortUrl.substr(17); //17 is the length of "http://tiny.url/"
        int n = base62ToBase10(shortUrl);
        return stol[n];
    }
};

// Your Solution object will be instantiated and called as such:
// Solution solution;
// solution.decode(solution.encode(url));


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值