shorten URL
如果url很多人添加情况怎么处理??
可否支持自定义url。
- 支持
- 不支持
用到了哪些字符:0-9,a-z,A-Z 62个字符
- 考虑不支持自定义url情况 首先将长url存到数据库中,并将id映射成62为底的短url。 2的6次方约等于62。如果是64的int,大概需要11位左右。 支持的操作有查询、插入。
- 支持自定义url 首先到table1查询如果没有,到自定义的table2查询。
需要考虑锁的情况,A用户插入了,但是B用户试图用相同的url,但是不能用了。如果用多个数据库,就会出现这种情况。
如果只是考虑很简单的整除62情况:
http://stackoverflow.com/questions/742013/how-to-code-a-url-shortener
// C++ prgram to generate short url from intger id and
// integer id back from short url.
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
// Function to generate a short url from intger ID
string idToShortURL(long int n)
{
// Map to store 62 possible characters
char map[] = "abcdefghijklmnopqrstuvwxyzABCDEF"
"GHIJKLMNOPQRSTUVWXYZ0123456789";
string shorturl;
// Convert given integer id to a base 62 number
while (n)
{
// use above map to store actual character
// in short url
shorturl.push_back(map[n%62]);
n = n/62;
}
// Reverse shortURL to complete base conversion
reverse(shorturl.begin(), shorturl.end());
return shorturl;
}
// Function to get integer ID back from a short url
long int shortURLtoID(string shortURL)
{
long int id = 0; // initialize result
// A simple base conversion logic
for (int i=0; i < shortURL.length(); i++)
{
if ('a' <= shortURL[i] && shortURL[i] <= 'z')
id = id*62 + shortURL[i] - 'a';
if ('A' <= shortURL[i] && shortURL[i] <= 'Z')
id = id*62 + shortURL[i] - 'A' + 26;
if ('0' <= shortURL[i] && shortURL[i] <= '9')
id = id*62 + shortURL[i] - '0' + 52;
}
return id;
}
// Driver program to test above function
int main()
{
int n = 12345;
string shorturl = idToShortURL(n);
cout << "Generated short url is " << shorturl << endl;
cout << "Id from url is " << shortURLtoID(shorturl);
return 0;
}
From http://www.geeksforgeeks.org/how-to-design-a-tiny-url-or-url-shortener/