Skip to content

Commit dda0e03

Browse files
authored
Merge pull request #2007 from AkifhanIlgaz/0535
Create: 0535-encode-and-decode-tinyURL.rs
2 parents 6b15c8f + 99b6928 commit dda0e03

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Diff for: rust/0535-encode-and-decode-tinyURL.rs

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
use std::collections::HashMap;
2+
3+
const BASE: &str = "http://tinyurl.com";
4+
5+
struct Codec {
6+
url_map: HashMap<String, String>,
7+
}
8+
9+
impl Codec {
10+
fn new() -> Self {
11+
Self {
12+
url_map: HashMap::new(),
13+
}
14+
}
15+
16+
// Encodes a URL to a shortened URL.
17+
fn encode(&mut self, longURL: String) -> String {
18+
let short_url = format!("{}{}", BASE, Self::generate_hash(&longURL));
19+
self.url_map.insert(short_url.clone(), longURL.clone());
20+
short_url
21+
}
22+
23+
// Decodes a shortened URL to its original URL.
24+
fn decode(&self, shortURL: String) -> String {
25+
self.url_map.get(&shortURL).unwrap().clone()
26+
}
27+
28+
fn generate_hash(url: &String) -> i32 {
29+
let mut hash = 5831;
30+
31+
for ch in url.chars() {
32+
hash = ((hash << 5) + hash) + (ch as i32);
33+
}
34+
35+
hash
36+
}
37+
}

0 commit comments

Comments
 (0)