现在需要实现一个长链接转短链接的算法。该算法会将原始长链接转换成一个以"https://short.url/"开头的、后接6位映射字符的短链接。算法描述如下: ① 计算key值。key初始为1,每次与64相乘后,和网址每一位字符的ASCII值相加,并每次对56800235584取余。 ② 遇到key值冲突则每次key值加1取余,直到不冲突为止。 ③ 建立key值与6位字符的映射。每一位依次从后往前是key对62取余后在字典"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"中对应的字符,每取一次后key值整除62再取。 ④ 映射字符不够六位,前面加'0'。 输入一个字符串数组表示要映射的长地址,第二个字符串数组表示要恢复的短地址,请将长地址转换成短地址,短地址转换成长地址。(要恢复的短地址一定是第一个数组的长地址转换过去的) 示例1 输入:["http:www.baidu.com","http://www.nowcoder.com"],["http://tiny.urleNm26h"] 返回值:["http://tiny.urleNm26h","http://tiny.urlJc7hPD","http:www.baidu.com"]用java代码实现
时间: 2023-02-14 10:28:20 浏览: 73
长链接转短链接
4星 · 用户满意度95%
以下是用 Java 语言实现的代码:
```
import java.util.HashMap;
public class ShortURL {
private static final String SHORT_URL_PREFIX = "https://short.url/";
private static final int DICTIONARY_LENGTH = 62;
private static final String DICTIONARY = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final long PRIME = 56800235584L;
private static HashMap<String, String> longToShortMap = new HashMap<>();
private static HashMap<String, String> shortToLongMap = new HashMap<>();
public static String[] longToShort(String[] urls) {
String[] shortUrls = new String[urls.length];
for (int i = 0; i < urls.length; i++) {
String longUrl = urls[i];
if (longToShortMap.containsKey(longUrl)) {
// 如果已经被转换过,直接返回已转换的短地址
shortUrls[i] = longToShortMap.get(longUrl);
} else {
long key = 1;
// 计算 key
for (int j = 0; j < longUrl.length(); j++) {
key = (key * 64 + (long)longUrl.charAt(j)) % PRIME;
}
// 遇到 key 冲突的情况
while (shortToLongMap.containsKey(key)) {
key = (key + 1) % PRIME;
}
// 建立 key 与 6 位字符的映射
StringBuilder shortUrlBuilder = new StringBuilder();
while (key > 0) {
shortUrlBuilder.insert(0, DICTIONARY.charAt((int)(key % DICTIONARY_LENGTH)));
key /= DICTIONARY_LENGTH;
}
// 映射字符不足 6 位,前面加 0
while (shortUrlBuilder.length() < 6) {
shortUrlBuilder.insert(0, '0');
}
String shortUrl = SHORT_URL_PREFIX + shortUrlBuilder.toString();
// 更新映射表
longToShortMap.put(longUrl, shortUrl);
shortToLongMap.put(shortUrl, longUrl);
shortUrls[i] = shortUrl;
}
}
return shortUrls;
}
public static String[] shortToLong(String[] urls) {
String[] longUrls = new String[urls.length];
for (int i = 0; i < urls.length; i++) {
阅读全文