<分区>
我想创建一个 URL 缩短服务,您可以在其中将长 URL 写入输入字段,该服务会将 URL 缩短为“http://www.example.org/abcdef
”。
可以使用包含 a-z、A-Z 和 0-9
的六个字符的任何其他字符串来代替“abcdef
”。这使得 56~570 亿个可能的字符串。
我的方法:
我有一个包含三列的数据库表:
- id,整数,自增
- long, string, 用户输入的长URL
- short,字符串,缩短的 URL(或只是六个字符)
然后我会将长 URL 插入表中。然后我会为“id
”选择自动增量值并构建它的散列。然后应将此散列作为“short
”插入。但是我应该构建什么样的哈希?像 MD5 这样的哈希算法会创建太长的字符串。我不使用这些算法,我想。自建算法也可以。
我的想法:
对于“http://www.google.de/
”,我得到自动递增 ID 239472
。然后我执行以下步骤:
short = '';
if divisible by 2, add "a"+the result to short
if divisible by 3, add "b"+the result to short
... until I have divisors for a-z and A-Z.
这可以重复,直到数字不再可整除。你认为这是一个好方法吗?你有更好的主意吗?
Due to the ongoing interest in this topic, I've published an efficient solution to GitHub, with implementations for JavaScript, PHP, Python and Java. Add your solutions if you like :)