Java 如何获取数组副本的位置
我目前有以下代码:Java 如何获取数组副本的位置,java,arrays,loops,nested,Java,Arrays,Loops,Nested,我目前有以下代码: String foxes = "The,Quick,Brown,Fox,Jumped,Over,The,Lazy,Dog."; System.out.println(" Here is the string unedited: " + foxes); String lowerCase = foxes.toLowerCase() .replaceAll("[\.:;'\"!\?]", " "); System.out.println(" Here is
String foxes = "The,Quick,Brown,Fox,Jumped,Over,The,Lazy,Dog.";
System.out.println(" Here is the string unedited: " + foxes);
String lowerCase = foxes.toLowerCase() .replaceAll("[\.:;'\"!\?]", " ");
System.out.println(" Here is the string (no caps + no punctuation): " + lowerCase);
List<String> foxesList = new ArrayList<String>(Arrays.asList(lowerCase.split(",")));
String foxs=“那个,快,布朗,狐狸,跳,过,那个,懒,狗。”;
System.out.println(“这是未编辑的字符串:“+fox”);
String lowerCase=foxes.toLowerCase().replaceAll(“[\:;”\“!\?]”,“”);
System.out.println(“这是字符串(无大写+无标点):”+小写);
List-foxesList=newarraylist(Arrays.asList(小写.split(“,”));
简而言之,此代码创建一个字符串
,使其不区分大小写,然后将其转换为数组
我现在需要找到数组中每个重复项的位置,我目前知道它与嵌套循环有关。重复项是发生2次的重复项。我需要知道这两个重复项的位置。您可以使用HashMap您可以使用:
HashMap(key: String, value: ArrayList)
存储字符串
其中arraylist将存储相应的索引
如果value.size()
代码:
HashMap<String, ArrayList<Integer>> dictMap = new HashMap<String, ArrayList<Integer>>();
String strArr[]={"Hi", "Foo", "Bar", "Foo"};
for(int i = 0; i < strArr.length; i++){
String str = strArr[i];
if(dictMap.containsKey(str)){
ArrayList<Integer> al = dictMap.get(str);
al.add(i);
}
else{
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(i);
dictMap.put(str, al);
}
}
HashMap dictMap=newhashmap();
字符串strArr[]={“Hi”,“Foo”,“Bar”,“Foo”};
对于(int i=0;i
查找重复索引的算法
创建字符串数组(通过将输入拆分为“”)
迭代数组并构建每个数组元素的映射,以列出其在映射中的位置。
3.最后你们在地图上有了所有的信息。对于每个你们有索引的条目,它都会出现。若它大于1,那个么它是重复的,而你们有索引
这里已经有一些正确的答案,假设您使用的是Java 8,让我给出一个更简洁的答案来创建地图:
Map<String, List<Integer>> map = new HashMap<>();
for (int i = 0; i < foxesList.size(); i++) {
String fox = foxesList.get(i);
map.computeIfAbsent(fox, f -> new ArrayList<>()).add(i);
}
Map Map=newhashmap();
对于(int i=0;inewArrayList()).add(i);
}
使用允许在地图中已经有列表和没有列表的情况下只有一行。很抱歉,我不完全理解您的意思,您能举个例子吗?添加了插入代码。请看一看。接下来,您需要遍历并检查每个地图条目,以查看arraylist大小是否大于1。非常感谢其他人想知道打印什么是简单的地图,然后给你答案。道具给你,这段代码真的很有帮助:)。
Map<String, List<Integer>> map = new HashMap<>();
for (int i = 0; i < foxesList.size(); i++) {
String fox = foxesList.get(i);
map.computeIfAbsent(fox, f -> new ArrayList<>()).add(i);
}