C#短網(wǎng)址算法
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
//62進(jìn)制
public static int BASE_NUM = 62;
//62進(jìn)制字母順序
public static final char[] array = {''G'', ''q'', ''w'', ''0'', ''H'', ''e'', ''T'', ''F'', ''9'', ''r'', ''V'', ''t'', ''y'', ''u'', ''N'', ''i'', ''6'', ''D'', ''o'', ''p'', ''L'', ''a'', ''s'', ''d'', ''K'', ''f'', ''g'', ''h'', ''j'', ''k'', ''4'', ''l'', ''z'', ''x'', ''c'', ''v'', ''b'', ''S'', ''n'', ''m'', ''1'', ''Z'', ''3'', ''5'', ''Q'', ''W'', ''E'', ''R'', ''7'', ''Y'', ''U'', ''I'', ''O'', ''2'', ''P'', ''A'', ''J'', ''X'', ''C'', ''B'', ''8'', ''M''};
/**
* 將10進(jìn)制數(shù)轉(zhuǎn)為62進(jìn)制字符串(短網(wǎng)址)
*
* @param number
* @return
*/
public static String getShortUrlByLongNum(Long number) {
Long rest = number;
Stack<Character> stack = new Stack<Character>();
StringBuilder result = new StringBuilder(0);
if (0 == rest) {
return String.valueOf(array[0]);
}
while (rest != 0) {
stack.add(array[new Long((rest - (rest / BASE_NUM) * BASE_NUM)).intValue()]);
rest = rest / BASE_NUM;
}
for (; !stack.isEmpty(); ) {
result.append(stack.pop());
}
return result.toString();
}
/**
* 通過(guò)短網(wǎng)址返回10進(jìn)制數(shù)
*
* @param shortUrl
* @return
*/
public static Long getLongNumByShortUrl(String shortUrl) {
long multiple = 1;
long result = 0;
Character c;
for (int i = 0; i < shortUrl.length(); i++) {
c = shortUrl.charAt(shortUrl.length() - i - 1);
result += valueOfCharacter(c) * multiple;
multiple = multiple * BASE_NUM;
}
return result;
}
/**
* 字母對(duì)應(yīng)的值 如array數(shù)組 G對(duì)應(yīng)0 q對(duì)應(yīng)1
*
* @param c
* @return
*/
private static int valueOfCharacter(Character c) {
for (int i = 0; i < array.length; i++) {
if (c == array[i]) {
return i;
}
}
return -1;
}
準(zhǔn)備一個(gè)被打亂的數(shù)組,存放A-Za-Z0-9這62個(gè)字符 ,預(yù)先產(chǎn)生一個(gè)網(wǎng)址ID,將這個(gè)ID通過(guò) _10_to_62 解析轉(zhuǎn)換成62進(jìn)制的短網(wǎng)址符。 存儲(chǔ)ID,短網(wǎng)址code,頁(yè)面URL 算法如下,很簡(jiǎn)單,時(shí)間效率也比較高,甚至,有了存儲(chǔ)的ID,要不要存儲(chǔ)短網(wǎng)址code都無(wú)所謂, 這個(gè)算法時(shí)間復(fù)雜度本來(lái)就是n,而一般的短網(wǎng)址長(zhǎng)度也就1~7位,時(shí)間復(fù)雜度也可以算作O(1)常量了。 該文章在 2021/1/29 17:11:11 編輯過(guò) |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |