C#短網(wǎng)址算法
當(dāng)前位置:點(diǎn)晴教程→知識管理交流
→『 技術(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();
}
/**
* 通過短網(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;
}
/**
* 字母對應(yīng)的值 如array數(shù)組 G對應(yīng)0 q對應(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)備一個被打亂的數(shù)組,存放A-Za-Z0-9這62個字符 ,預(yù)先產(chǎn)生一個網(wǎng)址ID,將這個ID通過 _10_to_62 解析轉(zhuǎn)換成62進(jìn)制的短網(wǎng)址符。 存儲ID,短網(wǎng)址code,頁面URL 算法如下,很簡單,時間效率也比較高,甚至,有了存儲的ID,要不要存儲短網(wǎng)址code都無所謂, 這個算法時間復(fù)雜度本來就是n,而一般的短網(wǎng)址長度也就1~7位,時間復(fù)雜度也可以算作O(1)常量了。 該文章在 2021/1/29 17:11:11 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |