gpt4 book ai didi

java - 在字符串列表中查找字谜词

转载 作者:行者123 更新时间:2023-12-01 23:29:32 25 4
gpt4 key购买 nike

我开发了以下程序来使用 java 中的 Hashmap 打印字谜。但无法弄清楚要在 map.put(); 行中放入什么内容以用于将条目插入 HashMap 。

import java.util.*;

class anagram
{
public static void main(String args[])
{
String temp;
int i,n;
Scanner s1=new Scanner(System.in);
List<Integer> temp2;
ArrayList<String> list=new ArrayList<String>();
HashMap<String,ArrayList<Integer>> map=new HashMap<String,ArrayList<Integer>>();
System.out.println("Enter the number of strings");
n=s1.nextInt();
//Input the strings and store them in Hashmap after sorting each
//string on character basis
//e.g hello , olleh are both stored as "ehllo" --> 0,1
//"ehllo" is sorted string and 0,1 are its keys
//In this way, at the end each bucket in hashmap will have anagrams
//which can be displayed on the basis of keys stored
for(i=0;i<n;i++)
{
temp=s1.next();
list.add(temp);
//what should I add here to input new string index into proper place
map.put();
}

//Iterating the hashmap to print values of each bucket
Iterator iterate=map.keySet().iterator();
while(iterate.hasNext())
{
Map.Entry entry=(Map.Entry)iterate.next();
temp2 =entry.getValue();
for(i=0;i<temp2.size;i++)
System.out.print(list.get(temp2.get(i))+" ");
}
list.clear();
}
//method to sort the string
private static String sort(String s)
{
char arr[]=s.toCharArray();
Arrays.sort(arr);
return String.valueOf(arr);
}
}

最佳答案

将索引存储为值似乎有开销。

您可以只存储输入值。 map 将是:

Map<String, Collection<String>> anagramsBySortedLettersInThem = ...

然后你可以使用“经典”模式:

String key = sort(inputString);

if (!anagramsBySortedLettersInThem.containsKey(key)) {
anagramsBySortedLetterInThem.put(key, new HashSet<String>);
}

anagramsBySortedLettersInThem.get(key).add(inputString);

我在这里使用Set,以避免重复。如果您需要重复 - 使用例如ArrayList

关于java - 在字符串列表中查找字谜词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19543152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com