1487.保证文件名唯一
链接:1487.保证文件名唯一
难度:Medium
标签:数组、哈希表、字符串
简介:返回长度为 n 的字符串数组,其中 ans[i] 是创建第 i 个文件夹时系统分配给该文件夹的实际名称。
题解 1 - cpp
- 编辑时间:2023-03-03
- 执行用时:168ms
- 内存消耗:57.2MB
- 编程语言:cpp
- 解法介绍:哈希存储。
class Solution {
public:
vector<string> getFolderNames(vector<string>& names) {
unordered_map<string, int> m;
for (int i = 0; i < names.size(); i++) {
string name = names[i];
if (m.count(name)) {
for (int j = m[name]; ; j++) {
string next = name + "(" + to_string(j) + ")";
if (!m.count(next)) {
names[i] = next;
m[next] = 1;
m[name] = j + 1;
break;
}
}
} else {
m[name] = 1;
}
}
return names;
}
};
题解 2 - python
- 编辑时间:2023-03-03
- 执行用时:140ms
- 内存消耗:28.3MB
- 编程语言:python
- 解法介绍:同上。
class Solution:
def getFolderNames(self, names: List[str]) -> List[str]:
m = {}
for i in range(len(names)):
name = names[i]
if name in m:
j = m[name]
while name + "(" + str(j) + ")" in m:
j += 1
next_name = name + "(" + str(j) + ")"
names[i] = next_name
m[next_name] = 1
m[name] = j + 1
else:
m[name] = 1
return names
题解 3 - rust
- 编辑时间:2023-03-03
- 执行用时:48ms
- 内存消耗:9.3MB
- 编程语言:rust
- 解法介绍:同上。
impl Solution {
pub fn get_folder_names(names: Vec<String>) -> Vec<String> {
let mut names = names;
let mut m = std::collections::HashMap::<String, usize>::new();
for i in 0..names.len() {
let name = names[i].clone();
if m.contains_key(&name) {
let mut j = *m.get(&name).unwrap();
let next;
loop {
let mut item = name.clone();
item.push('(');
item.push_str(&j.to_string());
item.push(')');
if !m.contains_key(&item) {
next = item;
break;
}
j += 1;
}
m.insert(next.clone(), 1);
names[i] = next.clone();
*m.get_mut(&name).unwrap() = j + 1;
} else {
m.insert(name.clone(), 1);
}
}
names
}
}