Skip to content

Commit

Permalink
Merge pull request neetcode-gh#2007 from AkifhanIlgaz/0535
Browse files Browse the repository at this point in the history
Create: 0535-encode-and-decode-tinyURL.rs
  • Loading branch information
tahsintunan authored Jan 13, 2023
2 parents 6b15c8f + 99b6928 commit dda0e03
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 dda0e03

Please sign in to comment.