java - Java(以及 Python)中字典的最佳数据结构

标签 java python

这是我的要求:

  • 输入:足够长的随机字符串,例如:fdjhkajajkfdj
  • 输出:fdj出现 2 次,并以 x 分隔字符

我想将所有三个字母的单词放入一个数组中并检查它们是否相同 例如:

a[0] = fdj
a[1] = djh
a[2] = jhk
a[3] = hka
a[4] = kaj
.
.
.
a[n] =fdj

我的答案是a[0]a[n]匹配,可能出现超过 2 次。

问题:那么我应该使用哪种数组在这种情况下是最佳的。我正在使用 Java(还有 python)。我正在考虑 Dict。

最佳答案

在 Java 中,您可以使用 Map 接口(interface) ( http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.html )

我会使用 HashMap,键是 3 个字母的单词,值是出现次数。这是一些示例伪代码

HashMap<String, int> wordCountMap = new HashMap<String, int>();
for(....) // for each 3 letter word in the input
{
    String word = ...; // current three letter word
    if(wordCountMap.containsKey(word))
        wordCountMap.put(word, wordCountMap.get(word)++);
    else
        wordCountMap.put(word, 1);
}

然后您可以循环遍历键/值对并返回它们的出现次数。

要返回单词之间的字符数,您可以在使用字符串操作计算出现次数后单独执行此操作(请参阅 String.indexOf)。伪代码是......

String orginalInput = "fdjhkajajkfdj";
String word = "fdj";
int firstOccurance = originalInput.indexOf();
int secondOccurance = originalInput.indexOf(firstOccurance+1);
int charsInBetween = secondOccurance - firstOccurance - 3; // difference in indices minus length of word

关于java - Java(以及 Python)中字典的最佳数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3809308/

相关文章:

java - Mac OS X 上的剪贴板监控 | java

java - jTextArea 垂直打印文本

java - 泛型和流 : How to make this into a `StreamTuple::new` statement?

python - 如何使用正则表达式检索非标准关键字属性的值,以将属性的值与 beautifulsoup 进行匹配?

python distutils : access to name of compiled extension

java - 硬编码访问 token 在谷歌电子表格 API 中不起作用?

java - 来自另一个属性的属性占位符位置(Spring 3.1)

python - 在 Matplotlib 中根据像素值设置透明度

python - 如何使用 gensim.similarities.Similarity 找到两个句子之间的相似性

Python plyfile 与 pymesh