java - 编码字符串数组
问题描述
编辑:[学校作业]
所以,我想只用 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 不同):(
谢谢!
解决方案
使用两级嵌套循环,您应该检查每个元素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]
推荐阅读
- node.js - 处理基于角色的权限时在哪里存储角色?
- haskell - 如何调试被“杀死”的堆栈进程?
- c# - SqlException:对象名无效,对象在运行时创建
- android - YoutubeExtractor Android 依赖错误
- php - 包含来自 Head 标签的脚本和资源的 PHP 文件(PHP 包含问题)
- reactjs - 在 ReactJS 中对表格进行分页
- next.js - __dirname 未在 API 路由中定义
- html - 我无法为我的身体设置颜色背景
- java - 在 Intellij Ultimate 中为简单的 Spring 应用程序设置 applicationContext.xml
- php - Woocommerce - 更改产品图库图片仅选择变体