-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0249_group_shifted_strings.rs
More file actions
65 lines (58 loc) · 1.84 KB
/
s0249_group_shifted_strings.rs
File metadata and controls
65 lines (58 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#![allow(unused)]
pub struct Solution {}
use std::collections::HashMap;
impl Solution {
// O(NM) N is the length of strings, M is length of string
pub fn group_strings(strings: Vec<String>) -> Vec<Vec<String>> {
let mut ret = HashMap::new();
for s in strings.into_iter() {
let key = Self::get_key(s.as_str());
let list = ret.entry(key).or_insert(vec![]);
list.push(s);
}
ret.into_iter()
.map(|(_, vals)| vals)
.collect::<Vec<Vec<String>>>()
}
fn get_key(s: &str) -> String {
let chs = s.chars().collect::<Vec<char>>();
let mut key = String::from("");
for i in 1..chs.len() {
let diff = chs[i] as i32 - chs[i - 1] as i32;
if diff < 0 {
let ch = 'a' as u32 + (diff + 26) as u32;
key.push(std::char::from_u32(ch).unwrap());
} else {
let ch = 'a' as u32 + diff as u32;
key.push(std::char::from_u32(ch).unwrap());
}
key.push(',');
}
key
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_249() {
// assert_eq!(
// Solution::group_strings(vec![
// "abc".to_string(),
// "bcd".to_string(),
// "acef".to_string(),
// "xyz".to_string(),
// "az".to_string(),
// "ba".to_string(),
// "a".to_string(),
// "z".to_string(),
// ],),
// vec![
// vec!["abc".to_string(), "bcd".to_string(), "xyz".to_string(),],
// vec!["az".to_string(), "ba".to_string(),],
// vec!["acef".to_string(),],
// vec!["a".to_string(), "z".to_string(),]
// ]
// );
}
}