D - Ananagrams|multimap的用法

本文探讨了Ananagrams的概念,即那些无论怎样重新排列字母都无法形成其他单词的词汇,并提供了一个程序解决方案来识别给定词典中的相对Ananagrams。通过对单词进行排序并比较,该程序能够有效地找出所有无法通过字母重组变成其他单词的独特词汇。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Ananagrams

Most crossword puzzle fans are used to anagrams — groups of words with the same letters in different orders — for example OPTS, SPOT, STOP, POTS and POST. Some words however do not have this attribute, no matter how you rearrange their letters, you cannot form another word. Such words are called ananagrams, an example is QUIZ.
Obviously such definitions depend on the domain within which we are working; you might think that ATHENE is an ananagram, whereas any chemist would quickly produce ETHANE. One possible domain would be the entire English language, but this could lead to some problems. One could restrict the domain to, say, Music, in which case SCALE becomes a relative ananagram (LACES is not in the same domain) but NOTE is not since it can produce TONE.
Write a program that will read in the dictionary of a restricted domain and determine the relative ananagrams. Note that single letter words are, ipso facto, relative ananagrams since they cannot be “rearranged” at all. The dictionary will contain no more than 1000 words.
Input
Input will consist of a series of lines. No line will be more than 80 characters long, but may contain any number of words. Words consist of up to 20 upper and/or lower case letters, and will not be broken across lines. Spaces may appear freely around words, and at least one space separates multiple words on the same line. Note that words that contain the same letters but of differing case are considered to be anagrams of each other, thus ‘tIeD’ and ‘EdiT’ are anagrams. The file will be terminated by a line consisting of a single ‘#’.
Output
Outputwillconsistofaseriesoflines. Eachlinewillconsistofasinglewordthatisarelativeananagram intheinputdictionary. Wordsmustbeoutputinlexicographic(case-sensitive)order. Therewillalways be at least one relative ananagram.
Sample Input
ladder came tape soon leader acme RIDE lone Dreis peat ScAlE orb eye Rides dealer NotE derail LaCeS drIed noel dire Disk mace Rob dries #
Sample Output
Disk
NotE
derail
drIed
eye
ladder
soon

题解

#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<algorithm>
#include<map>
#include<set>
using namespace std;
char ss[25], ori[25];
multimap<string, string> mapr;
set<string> setr;
multimap<string, string>::iterator itm;//map迭代器
set<string>::iterator its;//set迭代器
int main(){
	 int len, i;
 	while (scanf("%s",ss),ss[0]!='#') {//针对每个单词
  		strcpy(ori,ss);//ori保存原始顺序大小写的单词
  		len = strlen(ss);//单词长度
  		for (i = 0;i<len;++i) {
 			  if (isupper(ss[i]))//如果是大写就转小写
  		 ss[i] = tolower(ss[i]);
  		 sort(ss,ss+len);//给单词排序
  		 mapr.insert(make_pair(ss, ori));
 		 }
	 }
 	for (itm = mapr.begin(); itm != mapr.end(); ++itm)
 		 if (mapr.count(itm->first) == 1)
 	 		 setr.insert(itm->second);
 	for (its = setr.begin(); its != setr.end(); ++its)
 		 puts((*its).c_str());
 return 0;
}
<think>我们注意到用户的问题是关于Java中如何使用MultiMap。然而,在之前的对话中,我们讨论的是C++ STL中的multimap。根据用户当前的请求和提供的引用,我们需要转向Java中的MultiMap实现,特别是Guava库中的Multimap。 引用[1]提到了Guava的Multimap,引用[2]则涉及Java Multimap的一些实现细节(如线程安全性和统计值数量)。因此,我们将重点介绍Guava Multimap的使用。 步骤: 1. 引入Guava库 2. 创建Multimap实例 3. 添加键值对(允许重复键) 4. 获取键对应的所有值 5. 删除键值对 6. 其他常见操作(如统计、遍历等) 注意:由于Java标准库中没有MultiMap,我们通常使用第三方库(如Guava)或使用Map<K, List<V>>来模拟,但Guava的Multimap更为方便。 我们将按照以下结构组织回答: 一、引入Guava库 二、创建Multimap实例 三、添加键值对 四、获取值 五、删除操作 六、其他实用方法 七、线程安全性问题(引用[2]提到) 八、完整示例 同时,我们将生成相关问题。</think>### Java中MultiMap的使用详解 Java标准库未直接提供`MultiMap`,但可通过**Guava库**或**Apache Commons Collections**高效实现键值对的一对多映射。以下以Guava的`Multimap`为例详细说明: --- #### 一、核心依赖引入 在`pom.xml`中添加Guava依赖: ```xml <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>32.1.3-jre</version> <!-- 使用最新版本 --> </dependency> ``` --- #### 二、基础操作 ##### 1. 创建与插入 ```java import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; public class MultiMapDemo { public static void main(String[] args) { // 创建Multimap实例(键: String, 值: Integer) Multimap<String, Integer> scores = ArrayListMultimap.create(); // 插入键值对(允许重复键) scores.put("Alice", 85); scores.put("Bob", 90); scores.put("Alice", 92); // ✅ 允许重复键 scores.putAll("Charlie", Arrays.asList(88, 95)); // 批量插入 } } ``` ##### 2. 查询操作 | 操作 | 代码示例 | 说明 | |---------------------|-----------------------------------|--------------------------------------| | **获取所有值** | `Collection<Integer> aliceScores = scores.get("Alice");` | 返回`List`或`Set`(取决于实现类) | | **检查键存在** | `boolean exists = scores.containsKey("Bob");` | | | **统计值数量** | `int count = scores.get("Alice").size();` | 统计键对应的值数量[^2] | | **遍历所有键值对** | ```java for (Map.Entry<String, Integer> entry : scores.entries()) { System.out.println(entry.getKey() + ": " + entry.getValue()); }``` | 输出所有键值对 | --- #### 三、实现类选择 根据需求选择不同实现类: | 实现类 | 值存储结构 | 特点 | |----------------------------|---------------|------------------------------------| | `ArrayListMultimap` | `ArrayList` | 允许重复值,保留插入顺序 | | `HashMultimap` | `HashSet` | 值唯一,无序 | | `LinkedListMultimap` | `LinkedList` | 保留插入顺序,支持双向迭代 | | `TreeMultimap` | `TreeSet` | 值自动排序 | ```java // 示例:创建值唯一的Multimap Multimap<String, Integer> uniqueScores = HashMultimap.create(); ``` --- #### 四、高级操作 ##### 1. 删除键值对 ```java scores.remove("Bob", 90); // 删除指定键值对 scores.removeAll("Alice"); // 删除键对应的所有值 scores.clear(); // 清空所有数据 ``` ##### 2. 转换为标准Map ```java Map<String, Collection<Integer>> mapView = scores.asMap(); ``` ##### 3. 线程安全处理 ```java // 使用同步包装器(引用[2]) Multimap<String, Integer> safeMap = Multimaps.synchronizedMultimap(ArrayListMultimap.create()); ``` --- #### 五、完整示例 ```java import com.google.common.collect.*; public class StudentScores { public static void main(String[] args) { Multimap<String, Integer> scores = ArrayListMultimap.create(); scores.putAll("Alice", Arrays.asList(85, 92, 78)); scores.putAll("Bob", Arrays.asList(90, 88)); // 1. 获取Alice所有成绩 System.out.println("Alice的成绩: " + scores.get("Alice")); // [85, 92, 78] // 2. 删除Bob的88分 scores.remove("Bob", 88); // 3. 遍历输出 scores.forEach((k, v) -> System.out.println(k + " => " + v) ); /* 输出: Alice => 85 Alice => 92 Alice => 78 Bob => 90 */ } } ``` --- #### 六、与C++ STL的差异 | 特性 | C++ `multimap` | Guava `Multimap` | |---------------------|-------------------------|------------------------| | **底层结构** | 红黑树 | 自定义(如ArrayList) | | **值访问方式** | `equal_range()` | `get(key)` | | **线程安全** | 非线程安全 | 可通过包装器实现[^2] | | **重复值支持** | 仅键重复 | 键和值均可重复 | > **注意**:Guava的`Multimap`不是`java.util.Map`的子接口,而是独立设计的一对多映射接口[^1]。 --- #### 七、最佳实践 1. **选择合适实现**:需值唯一用`HashMultimap`,需排序用`TreeMultimap` 2. **避免空键**:`Multimap`不允许`null`键(允许`null`值) 3. **性能考量**:`ArrayListMultimap`的插入$O(1)$,查找$O(n)$;`TreeMultimap`插入/查找均为$O(\log n)$
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值