Skip to content

Commit 99b6928

Browse files
committed
Create: 0535-encode-and-decode-tinyURL.rs
1 parent ee7a3bc commit 99b6928

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
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)
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