【发布时间】:2021-04-20 23:58:58
【问题描述】:
编辑:[学校作业]
所以,我想只用 0 和 1 对单词进行编码。
0 = 单词不存在
1 = 出现的单词
我的字典对应:
String[] dictionary = {"Hello", "I", "am", "Lukas", "and", "Jonas", "play", "football"};
例如:如果我对这些词进行编码...
String[] listOfWords = {"Hello", "play" "football"};
我必须有以下数组:
int[] wordsEncode = {1,0,0,0,0,0,1,1};
您可以看到“Hello”出现了,“I”“am”“Lukas”“和”“Jonas”没有出现。最后,出现了“play”和“football”。
我们必须保持字典的顺序,这是我代码中的问题。
我真的不知道如何解决这个问题(使用第二个 for 循环?)?
我认为 wordEncode[i] 是我的错误,但如何解决呢?
这是我的代码:
class Dictionary {
/**
* Array words Dictionary
*/
String[] dictionary;
/**
* Maximum of words MAX_WORDS
*/
final int MAX_WORDS = 50;
/**
* Number of words in the dictionary
*/
int numberWordsDictionary;
/**
* Constructor
*/
Dictionary() {
dictionary = new String[MAX_WORDS];
numberWordsDictionary = 0;
}
int[] encoder(String[] listOfWords) {
int[] wordsEncode = new int[numberWordsDictionary];
StringBuilder builder = new StringBuilder();
for(String word : dictionary) {
builder.append(word);
}
String dictionaryString = builder.toString();
for(int i = 0; i < listOfWords.length; i++) {
if(dictionaryString.contains(listOfWords[i])) {
wordsEncode[i] = 1;
} else {
wordsEncode[i] = 0;
}
}
return wordsEncode;
}
}
抱歉缩进(与我的 Java IDE 不同):(
谢谢!
【问题讨论】:
-
如果输入的是
{"football", "play", "Hello"};怎么办? -
如果这是学校作业,你应该说做。这会影响什么样的答案是合适的。
-
你当然应该按照作业的要求去做。只是让你知道,这不是人们在现实生活中会使用的数据结构。 Anti-pattern: parallel collections.