短网址算法实现

短网址或微小的网址是用来表示长URL的URL。 例如,http://tinyurl.com/y9nyxza
将重定向到http://www.iteye.com/topic/577820


使用短网址的主要优点:

1.便于记忆,而不是记50个或多个字符的URL
2.当你想通过短信发送一个50个字符的URL给朋友,你只留下您的信息90个字符。


实现自己的短网址需要如下步骤:

1.定义您自己的网址映射算法。
2.有一个数据库来存储映射的网址。
3.从数据库的短网址的映射找到原始的URL

我不知道别人是如何创建URL映射算法,但在这里,我将告诉你们,我的简单而快速的短网址实现:

该系统使用6个短码字符来表示任何长度的网址。 有效的字符代码是ASCII 'A'到'Z'和'0'的'5',其中每个字符包含2 ^ 5(32)状态。  6短码字符可用于绘制32 ^ 6(1073741824)的网址

首先,你需要一个数据库表来存储和检索你映射的网址。 


CREATE TABLE mappedURL (的CREATE TABLE mappedURL(
shortCode char(6) not null,
lognURL  text not null,
PRIMARY KEY  shortCodeInd (shortCode),
);

其次,你需要定义一个算法将长的URL映射到短的URL。 以下是建议的算法:


loop1: while true loop1:
  calculate md5 of the URL
  loop2: from 1st 4 bytes to 4th 4 bytes of md5 result loop2:
    cast the 4 bytes to an integer
    loop3: for shortCodeChar[0] to shortCodeChar[5]
      use 1st 5 bits of the integer to find the value in codeMap
      remove 5 bits from the integer
    end loop3
    save shortCodeChar as shortCode
    if shorCode does not exist in database
      insert the short code and original URL into database
      break loop1:
    else
      retrieve the stored URL from database
      if original URL equals to URL stored in database
        break loop1:
      end if
    end if
  end loop2
  insert '-'
end loop1
return shortCode

Note: codeMap contains value of valid characters from 'a' to 'z' (index 0 to 25) and '0'-'5' (index 26 to 31).

第三,你需要创建一个网页,从数据库的短网址的映射找到原始的URL,并重定向之。

你可能感兴趣的:(算法,PHP,新浪微博,twitter)