sadiqul_amin

535. Encode and Decode TinyURL

Apr 24th, 2022
1,216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.83 KB | None | 0 0
  1. // https://leetcode.com/problems/encode-and-decode-tinyurl
  2. // 535. Encode and Decode TinyURL
  3.  
  4.  
  5. public class Codec {
  6.     String chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  7.     HashMap<String, String> map = new HashMap<>();
  8.     int count = 1;
  9.  
  10.     public String getString() {
  11.         int c = count;
  12.         StringBuilder sb = new StringBuilder();
  13.         while (c > 0) {
  14.             c--;
  15.             sb.append(chars.charAt(c % 62));
  16.             c /= 62;
  17.         }
  18.         return sb.toString();
  19.     }
  20.  
  21.     public String encode(String longUrl) {
  22.         String key = getString();
  23.         map.put(key, longUrl);
  24.         count++;
  25.         return "http://tinyurl.com/" + key;
  26.     }
  27.  
  28.     public String decode(String shortUrl) {
  29.         return map.get(shortUrl.replace("http://tinyurl.com/", ""));
  30.     }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment