From 99b6928d24596cf4095c806a4e6ffcc67d61af25 Mon Sep 17 00:00:00 2001 From: AkifhanIlgaz Date: Fri, 13 Jan 2023 00:37:56 +0300 Subject: [PATCH] Create: 0535-encode-and-decode-tinyURL.rs --- rust/0535-encode-and-decode-tinyURL.rs | 37 ++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 rust/0535-encode-and-decode-tinyURL.rs diff --git a/rust/0535-encode-and-decode-tinyURL.rs b/rust/0535-encode-and-decode-tinyURL.rs new file mode 100644 index 000000000..ebc3b6731 --- /dev/null +++ b/rust/0535-encode-and-decode-tinyURL.rs @@ -0,0 +1,37 @@ +use std::collections::HashMap; + +const BASE: &str = "http://tinyurl.com"; + +struct Codec { + url_map: HashMap, +} + +impl Codec { + fn new() -> Self { + Self { + url_map: HashMap::new(), + } + } + + // Encodes a URL to a shortened URL. + fn encode(&mut self, longURL: String) -> String { + let short_url = format!("{}{}", BASE, Self::generate_hash(&longURL)); + self.url_map.insert(short_url.clone(), longURL.clone()); + short_url + } + + // Decodes a shortened URL to its original URL. + fn decode(&self, shortURL: String) -> String { + self.url_map.get(&shortURL).unwrap().clone() + } + + fn generate_hash(url: &String) -> i32 { + let mut hash = 5831; + + for ch in url.chars() { + hash = ((hash << 5) + hash) + (ch as i32); + } + + hash + } +} pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy