question:
Note: This is a companion problem to the System Design problem: Design TinyURL.
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl
and it returns a short URL such as http://tinyurl.com/4e9iAk
.
Design the encode
and decode
methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
ideas :
We can use the hash algorithm to store Key and value, key: http://tinyurl.com + random number, value: the LongURL, the key point is how to produce 6 random numbers,We have two methods, the first is to generate a random number using an array containing uppercase and lowercase letters and numbers, and the second is to generate a random number with reference to the Ascll table.
one
public static String verifyCode(){
String str = "";
char[] ch = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
Random random = new Random();
for (int i = 0; i <6; i++){
char num = ch[random.nextInt(ch.length)];
str += num;
}
return str;
Two
public static String verifyCode() {
Random random = new Random();
String str = ""; //为了减少对象的生成,使用StringBuffer更好
for (int i = 0; i < 6; i++){
int key = random.nextInt(3);
switch (key){
case 0:
int code1 = random.nextInt(10);
str += code1;
break;
case 1:
char code2 = (char)(random.nextInt(26)+65);
str += code2;
break;
case 2:
char code3 = (char)(random.nextInt(26)+97);
str += code3;
break;
}
}
return str;
final:
public class Codec {
// Encodes a URL to a shortened URL.
//储存long和shorturl
HashMap<String,String > map =new HashMap<String ,String >();
String prefix ="http://tinyurl.com/" ;
public String encode(String longUrl) {
Random random = new Random();
String code ="";
for (int i = 0; i < 6; i++){
int key=random.nextInt(3);
switch (key){
case 0:
int code1 = random.nextInt(10);
code += code1;
break;
case 1:
char code2 = (char)(random.nextInt(26)+65);
code += code2;
break;
case 2:
char code3 = (char)(random.nextInt(26)+97);
code += code3;
break;
}
}
map.put(code,longUrl);
return prefix+code;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
String shortCode=shortUrl.substring(shortUrl.length()-6);
return map.get(shortCode);
}
网友评论