Q52 Encode and Decode TinyURL - LeetCode
Tue Jan 31 2023 02:20:16 GMT+0000 (UTC)
Saved by
@Ayush_dabas07
public class Codec {
HashMap<String,String> map ; //<LongUrl,ShortUrl>
//constructor
public Codec(){
this.map = new HashMap<>();
}
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
//making a random number throuhg math.encoding eg: 53.15 and round it off
//after rounding it off change it into ascii character , it that character
//exists in the HM add another random character to the stringbuilder
//untill it is not contained in the HM
//use SB as operations in SB are in O(1) and in string is o(n)
StringBuilder shortUrl = new StringBuilder();
shortUrl.append((char)(Math.floor(Math.random()*100)));
while(map.containsKey(shortUrl))
shortUrl.append((char)(Math.floor(Math.random()*100)));
map.put(shortUrl.toString(),longUrl);
return shortUrl.toString();
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
String longUrl = map.get(shortUrl);
return longUrl.toString();
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));
content_copyCOPY
https://leetcode.com/problems/encode-and-decode-tinyurl/
Comments