2451.差值数组不同的字符串
链接:2451.差值数组不同的字符串
难度:Easy
标签:数组、哈希表、字符串
简介:给你一个字符串数组 words ,每一个字符串长度都相同,令所有字符串的长度都为 n 。
题解 1 - rust
- 编辑时间:2023-05-25
- 内存消耗:2.1MB
- 编程语言:rust
- 解法介绍:同上。
pub fn str_to_vec(s: &String) -> Vec<char> {
    s.chars().collect()
}
impl Solution {
    pub fn odd_string(words: Vec<String>) -> String {
        let mut m = std::collections::HashMap::<String, Vec<String>>::new();
        for w in words {
            let mut key = String::new();
            {
                let w: Vec<char> = str_to_vec(&w);
                for i in 0..w.len() - 1 {
                    key.push((w[i + 1] as u8 - w[i] as u8 + b'0') as char);
                }
            }
            m.entry(key).or_insert(vec![]).push(w);
        }
        for (_, list) in m.into_iter() {
            if list.len() == 1 {
                return list[0].clone();
            }
        }
        String::new()
    }
}
题解 2 - cpp
- 编辑时间:2023-05-25
- 执行用时:4ms
- 内存消耗:7.4MB
- 编程语言:cpp
- 解法介绍:哈希存储。
class Solution {
public:
    string oddString(vector<string>& words) {
        unordered_map<string, vector<string>> m;
        for (auto &w : words) {
            string key = "";            
            for (int i = 0; i < w.size() - 1; i++) key += to_string(w[i + 1] - w[i] + '0');
            m[key].push_back(w);
        }
        for (auto &item : m) {
            if (item.second.size() == 1) return item.second[0];
        }
        return words[0];
    }
};
题解 3 - python
- 编辑时间:2023-05-25
- 执行用时:48ms
- 内存消耗:15.9MB
- 编程语言:python
- 解法介绍:同上。
class Solution:
    def oddString(self, words: List[str]) -> str:
        m = dict()
        for w in words:
            key = ""
            for i in range(len(w) - 1):
                key += chr(ord(w[i + 1]) - ord(w[i]) + ord('0'))
            if not key in m: m[key] = []
            m[key].append(w)
        for v in m.values():
            if len(v) == 1:
                return v[0]
        return words[0]