Skip to content

Commit

Permalink
Create: 0535-encode-and-decode-tinyURL.rs
Browse files Browse the repository at this point in the history
  • Loading branch information
AkifhanIlgaz committed Jan 12, 2023
1 parent ee7a3bc commit 99b6928
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions rust/0535-encode-and-decode-tinyURL.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use std::collections::HashMap;

const BASE: &str = "http://tinyurl.com";

struct Codec {
url_map: HashMap<String, String>,
}

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
}
}

0 comments on commit 99b6928

Please sign in to comment.