这是我的要求:
- 输入:足够长的随机字符串,例如:
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/