-
Notifications
You must be signed in to change notification settings - Fork 0
/
ShortUrl.java
77 lines (61 loc) · 1.71 KB
/
ShortUrl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import java.util.HashMap;
import java.util.Random;
import java.math.*;
import java.lang.*;
public class MyClass
{
public static void main(String[] args) {
shortURL toShortUrl = new shortURL("https://www.yahoo.com");
String shorturl=toShortUrl.getBase62From10();
System.out.println(shorturl);
String originalURL =toShortUrl.getBase10From62("http://fkt.in/ABC");
System.out.println(originalURL);
}
}
class shortURL{
final char[] corpus = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
HashMap<Integer, String> valueMap=new HashMap<Integer, String>();
String domain = "https://fkt.in";
String url = "";
Random rand=new Random();
int seed=101646;
shortURL(String url){
valueMap.put(seed,url);
url = url.substring(7);
this.url = url;
}
public final String getBase62From10()
{
String number = seed + "";
String code="";
char[] buf = new char[number.length()];
int charPos = number.length() - 1;
BigInteger bigIntegerNumber = new BigInteger(number);
BigInteger radix = BigInteger.valueOf(62);
while (bigIntegerNumber.compareTo(radix) >= 0)
{
buf[charPos--] = corpus[bigIntegerNumber.mod(radix).intValue()];
bigIntegerNumber = bigIntegerNumber.divide(radix);
}
buf[charPos] = corpus[bigIntegerNumber.intValue()];
code=new String(buf, charPos, (number.length() - charPos));
return domain + "/" +code;
}
public final String getBase10From62(String shortURL){
int i=0;
int decimal=0;
int pos = shortURL.lastIndexOf("/");
shortURL= shortURL.substring(pos+1);
char[] url = shortURL.toCharArray();
for(int j=0;j<url.length;j++){
i=0;
for(char c:corpus){
if(c==url[j]){
decimal+=i*Math.pow(62,url.length-j-1);
}
i=i+1;
}
}
return valueMap.get(decimal);
}
}