forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request neetcode-gh#2007 from AkifhanIlgaz/0535
Create: 0535-encode-and-decode-tinyURL.rs
- Loading branch information
Showing
1 changed file
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |