Guest User

Untitled

a guest
May 5th, 2018
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. import java.util.HashMap;
  2. import java.util.Random;
  3. import java.lang.StringBuilder;
  4.  
  5. public class Codec {
  6.  
  7. //HashMap to store the longUrl and the randomly generated string
  8. HashMap<String,String> urlMap = new HashMap<>();
  9.  
  10. // Encodes a URL to a shortened URL.
  11. public String encode(String longUrl) {
  12. Random rand = new Random();
  13. int urlLen = 6;
  14. char [] shortURL = new char[urlLen];
  15. String randChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
  16.  
  17. for(int i = 0; i < urlLen; i++ )
  18. shortURL[i] = randChars.charAt(rand.nextInt(randChars.length()));
  19.  
  20. StringBuilder sb = new StringBuilder("http://tinyurl.com/");
  21. sb.append(new String(shortURL));
  22. System.out.println(sb);
  23.  
  24. urlMap.put(sb.toString(),longUrl);
  25.  
  26. return sb.toString();
  27.  
  28. }
  29.  
  30. // Decodes a shortened URL to its original URL.
  31. public String decode(String shortUrl) {
  32.  
  33. return urlMap.get(shortUrl);
  34.  
  35. }
  36. }
  37.  
  38. // Your Codec object will be instantiated and called as such:
  39. // Codec codec = new Codec();
  40. // codec.decode(codec.encode(url));
Add Comment
Please, Sign In to add comment