gpt4 book ai didi

java - 删除数组中重复的单词句子

转载 作者:行者123 更新时间:2023-12-02 10:38:00 27 4
gpt4 key购买 nike

给定一个确定单词的输出、每个单词的长度以及单词重复次数的问题,我有以下代码能够确定下面的单词和每个单词的长度:

String sentence;
String charSentence;
String[] wordOutput;

private void analyzeWords(String s) {
String[] words = sentence.split(" ");
wordOutput = new String[words.length];
int[] repeats = new int[words.length];

// Increment a single repeat
for (int i = 0; i < words.length; i++) {

repeats[i] = 1;

// Increment when repeated.
for (int j = i + 1; j < words.length - 1; j++) {
if (words[i].equalsIgnoreCase(words[j])) {
repeats[i]++;
}
}

wordOutput[i] = words[i] + "\t" + words[i].length() + "\t" + repeats[i];
}

当我运行该程序时,我得到以下输出:

Equal   5   2
Equal 5 1 <- This is a duplicate word and should not be here when it repeats.

有人知道我的问题出在哪里吗?它与我的重复数组有关吗?

最佳答案

第一个问题是,在内部 for 循环中,您从 i+1 循环到 length-1。您需要循环直到length。其次,您需要确定 String 中是否出现了该单词,如果是,则使用 continue 语句。你可以这样做:

outer:
for (int i = 0; i < words.length; i++) {

repeats[i] = 1;
for(int index = i-1; index >= 0; index--) {
if(words[i].equals(words[index])) {
continue outer;
}
}
...
}

但是,这样做的问题是,当您指定长度与单词数相同的 Array 时,列表末尾将出现 null 值。要解决这个问题,你可以这样做:

 wordOutput = Arrays.stream(wordOutput).filter(e-> e!= null).toArray(String[]::new);

这将过滤掉null

输出:

(输入字符串:“这是一个字符串,其中有很多重复”)

This    4   2
is 2 2
a 1 3
String 6 1
with 4 1
lot 3 2
of 2 1
this 4 1
repeats 7 2

关于java - 删除数组中重复的单词句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53137222/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com