首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在不使用Stream API、MAP、Hashset、collection API的情况下统计已经排序的ArrayList中每个字符串的出现频率

如何在不使用Stream API、MAP、Hashset、collection API的情况下统计已经排序的ArrayList中每个字符串的出现频率
EN

Stack Overflow用户
提问于 2019-04-24 16:32:03
回答 2查看 69关注 0票数 1

我已经尝试使用下面的代码,虽然它可以工作,但不能满足requirement.Please分享您的知识,谢谢

代码语言:javascript
复制
String temp;                                
for(int i = 0; i < lexicon.size(); i++)
{
    for (int j = lexicon.size() - 1; j > i; j--)
    {
        if (lexicon.get(i).compareTo(lexicon.get(j)) > 0)
        {
            temp  = lexicon.get(i);
            lexicon.set(i,lexicon.get(j)) ;
            lexicon.set(j,temp);
        }
    }
}


ArrayList<String> uniqueWords = new ArrayList<String>();

for(int i = 0; i < lexicon.size(); i++)       //Removing duplicates 
{
    int wordCount = 1;
    uniqueWords.add(lexicon.get(i));
    for(int j = i+1; j < lexicon.size(); j++)
    {
        if(uniqueWords.get(i).equals(lexicon.get(j)))
        {
            wordCount++;
            lexicon.remove(j);
        }
    }
    System.out.println(uniqueWords.get(i) + "  " + wordCount);
}

这是我得到的输出:

代码语言:javascript
复制
a  6
a  3
a  2
about  1
acknowledged  1
all  1
also  1
and  2
answer  1
at  2
austen  1
be  2
been  1
bennet  2
bennet  1

我需要这样的东西:那个词的字数统计

代码语言:javascript
复制
a 11
about 1
acknowledge 1

诸若此类

EN

回答 2

Stack Overflow用户

发布于 2019-04-24 17:00:01

问题是,你在lexicon.remove(j);上删除了你的词典中的元素,并在lexicon.get(j)上检查了你的词典

我不想给你完整的代码,因为你不会从中学到任何东西,但我希望我给了你足够的提示,来解决你的问题。尝试调试您的代码,看看变量发生了什么:)

票数 1
EN

Stack Overflow用户

发布于 2019-04-24 17:01:10

在索引j处删除时,j get的值增加了j++,实际上跳过了一个值,而这个值本应继续而不增加。

正如已经排序的:

代码语言:javascript
复制
String word = uniqueWords.get(i);
int j = i+1;
while (j < lexicon.size() && word.equals(lexicon.get(j)))
{
    wordCount++;
    lexicon.remove(j);
}

(我将给出代码,因为它显示了一种稍微不同的方法。)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55825656

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档