首页 > 解决方案 > 编码字符串数组

问题描述

编辑:[学校作业]

所以,我想只用 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 不同):(
谢谢!

标签: javaarraysstringencode

解决方案


使用两级嵌套循环,您应该检查每个元素dictionary[]是否存在listOfWords[],如果存在,则将相应索引处的值更新wordsEncode[]1

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String[] dictionary = { "Hello", "I", "am", "Lukas", "and", "Jonas", "play", "football" };
        String[] listOfWords = { "Hello", "play", "football" };
        int[] wordsEncode = new int[dictionary.length];

        for (int i = 0; i < dictionary.length; i++) {
            boolean found = false;
            for (String s : listOfWords) {
                if (s.equals(dictionary[i])) {
                    found = true;
                    break;
                }
            }
            if (found) {
                wordsEncode[i] = 1;
            }
        }

        // Display the result
        System.out.println(Arrays.toString(wordsEncode));
    }
}

输出:

[1, 0, 0, 0, 0, 0, 1, 1]

推荐阅读