2019年9月14日
这次碰到了加密算法的题目,恰好我之前也自己完成过“短链接服务”的开发,然后也部署到服务器了,顺手解决它吧。
目录
题目:
解决方法1:
package leetCode.middle.tiny_url;
/**
* @author moubin.mo
* @date: 2019/9/14 15:30
*/
public class TinyURL {
private static final char SECRET_KEY = 8;
public static void main(String[] args){
String longUrl = "https://leetcode.com/problems/design-tinyurl";
String shortUrl1 = encode(longUrl);
String longUrl1 = decode(shortUrl1);
System.out.println(longUrl.equals(longUrl1));
}
// Encodes a URL to a shortened URL.
public static String encode(String longUrl) {
// 将需要加密的内容转换为字节数组
byte[] bt = longUrl.getBytes();
for(int i = 0; i < bt.length; i++){
// 通过异或运算进行加密
bt[i] = (byte)(bt[i] ^ (int)SECRET_KEY);
}
// 将加密后的字符串保存到 newresult 变量中
String newresult = new String(bt, 0, bt.length);
return newresult;
}
// Decodes a shortened URL to its original URL.
public static String decode(String shortUrl) {
// 将需要加密的内容转换为字节数组
byte[] bt = shortUrl.getBytes();
for(int i = 0; i < bt.length; i++){
// 通过异或运算进行加密
bt[i] = (byte)(bt[i] ^ (int)SECRET_KEY);
}
// 将加密后的字符串保存到 newresult 变量中
String newresult = new String(bt, 0, bt.length);
return newresult;
}
}
性能
解题思路:
- 二进制的两次异或运算是其本身。
解决方法2:
public class Codec {
private static int key=35;
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
char[] c=longUrl.toCharArray();
for (int i=0;i<c.length;i++)
{
c[i]^=key;
}
String encode = new String(c);
return "http://"+encode;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
char[] c=shortUrl.substring(7).toCharArray();
for (int i=0;i<c.length;i++)
{
c[i]^=key;
}
return new String(c);
}
}
解决方法3:
JAVA实现: tinyurl 格式: http://tinyurl.com/ + 6位随机码(4e9iAK) 使用哈希表map, 加密的时候生成随机 tinyurl, 若 tinyurl 在 map中不存在, 则以 tinyurl 作为 key, url 作为value; 解密时, 通过 tinyurl 作为 key, 即可找到作为 value 的 url.
public class HashMapStoreUrl {
Map<String, String> map = new HashMap<String, String>();
static final String INDEX = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
static final String TINYURL_PREFIX = "http://tinyurl.com/";
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
char[] chs = new char[6];
while(true){
for(int i = 0; i < 6; i++){
chs[i] = INDEX.charAt((int)(Math.random()*62));
}
String shortUrl = TINYURL_PREFIX + new String(chs);
if(!map.containsKey(shortUrl)){
map.put(shortUrl, longUrl);
return shortUrl;
}
}
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return map.get(shortUrl);
}
}
解决方法4:(搞笑的)
public class Codec {
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
return longUrl;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return shortUrl;
}
}