打印字符串中重复次数最多的单词



编写一个java程序来查找字符串中重复次数最多的单词,并打印其频率。


输入

你是吗

输出

是:2


这个问题可以通过使用HashMap或文件读取器来完成(我想(,但实际上,我还没有学会。

然而,我设法写了一个代码,显示频率(但不是单词(

import java.util.Scanner;
class duplicatewords
{
void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
String str=sc.nextLine();
String arr[]=str.split(" ");
int count=1; int checkvalue=0;
for(int i=0;i<arr.length-1;i++)
{
String temp=arr[i];
for(int j=i+1;j<arr.length;j++)
{
String anothertemp=arr[j];
if(temp.equalsIgnoreCase(anothertemp))
count++;
}
if(checkvalue<c)
checkvalue=c;
c=1;
}
System.out.println(checkvalue);
}
} 

我想知道如何在不使用任何地图或阅读器的情况下打印单词。

我认为这个项目会很复杂,但我会理解的。

任何帮助都将不胜感激。

事实上,为了获得最频繁的单词,需要稍微修改现有代码,为最重复的变量提供一个变量,当检测到更频繁的单词时,必须更新该变量。此特定任务不需要额外的数组/数据结构。

String arr[] = str.split(" ");
int maxFreq = 0;
String mostRepeated = null;
for (int i = 0; i < arr.length; i++) {
String temp = arr[i];
int count = 1;
for (int j = i + 1; j < arr.length; j++) {
if (temp.equalsIgnoreCase(arr[j]))
count++;
}
if (maxFreq < count) {
maxFreq = count;
mostRepeated = temp;
}
}
System.out.println(mostRepeated + ": " + maxFreq);

对于输入:

String str = "I am he as you are he as you are me and we are all together";

输出:

are: 3

一个更快的实现可以包括将重复值设置为null以稍后跳过它们:

for (int i = 0; i < arr.length; i++) {
if (null == arr[i]) continue;
String temp = arr[i];
int count = 1;
for (int j = i + 1; j < arr.length; j++) {
if (temp.equalsIgnoreCase(arr[j])) {
count++;
arr[j] = null;
}
}
if (maxFreq < count) {
maxFreq = count;
mostRepeated = temp;
}
}

这是我使用两个数组的解决方案:

public static void main(String[] args) {
String input = "are you are";
String[] words = input.split(" ");
//the 10 is the limit of individual words:
String[] wordsBucket = new String[10];
Integer[] countBucket = new Integer[10];
for(String word:words){
int index = findIndex(word, wordsBucket);
incrementIndex(countBucket, index);
}
int highest = findMax(countBucket);
System.out.println(wordsBucket[highest]+": "+countBucket[highest]);
}
private static int findMax(Integer[] countBucket) {
int max = 0;
int maxIndex = 0;
for(int i=0;i<countBucket.length;i++) {
if(countBucket[i]==null) {
break;
}
if(countBucket[i] > max) {
max = countBucket[i];
maxIndex = i;
}
}
return maxIndex;
}
private static int findIndex(String word, String[] wordsBucket) {
for(int i=0;i<wordsBucket.length;i++) {
if(word.equals(wordsBucket[i])) {
return i;
}
if(wordsBucket[i] == null) {
wordsBucket[i] = word;
return i;
}
}
return -1;
}
private static void incrementIndex(Integer[] countBucket, int index) {
if(countBucket[index] == null){
countBucket[index] = 1;
} else {
countBucket[index]++;
}
}

这将打印are: 2。正如@knittl在评论中指出的那样,这也可以用1个Pair<String, Integer>数组或类似的东西来完成。

如果允许您使用Map和流,那么这也可以(使用与上述相同的String[] words作为输入(:

Map<String, Integer> countingMap = new HashMap<>();
Arrays.stream(words).forEach(w->countingMap.compute(w, (ww,c)->c==null?1:c+1));
Map.Entry<String, Integer> h = countingMap.entrySet().stream().sorted(Comparator.comparingInt(Map.Entry<String,Integer>::getValue).reversed()).findFirst().get();
System.out.println(h);

这将打印are=2

这里有一种方法。它只是维护一个单词列表,以便在遍历列表时计数和调整最大值。

  • scratch数组被分配到最大字数
  • CCD_ 7被调整为基于所发现的字来控制通过更新的阵列的迭代
String s =
"this when this how to now this why apple when when other now this now";
String[] words = s.split("\s+");
int cnt = 0;
int idx = -1;
String[] list = new String[words.length];
int[] count = new int[words.length];
int max = 0;
for (int i = 0; i < words.length; i++) {
for (int k = 0; k < cnt; k++) {
if (list[k].equals(words[i])) {
count[k]++;
if (count[k] > max) {
max = count[k];
idx = k;
}
break;
}
}
count[cnt] = 1;
list[cnt++] = words[i];
}
System.out.println(words[idx] + " " + max);

打印

this 4

这里还有另一个使用流的解决方案。这只需创建单词计数的映射,然后找到计数最大的第一个条目。领带被忽略。

Entry<String, Integer> result = Arrays.stream(s.split("\s+"))
.collect(Collectors.toMap(r -> r, q -> 1,
(a, b) -> a + 1))
.entrySet().stream().max(Entry.comparingByValue())
.get();
System.out.println(result);

打印

this=4

有两种解决方案,但一种比另一种更好。

解决方案一:使用Map<String, Integer>

public class WordCount {
public static void main(String[] args) {
String phrase = "This example is very good but is not very efficient";
String[] words = phrase.split(" ");
List<String> wordList = Arrays.asList(words);

Map<String, Integer> wordCountMap = wordList.parallelStream().
collect(Collectors.toConcurrentMap(
w -> w, w -> 1, Integer::sum));

System.out.println(wordCountMap);
}
}

这会产生以下输出:

{but=1, very=2, not=1, efficient=1, This=1, is=2, good=1, example=1}

正如您所看到的,veryis并列为最频繁的单词。这就是为什么这种解决方案不是最有效的。如果你可以颠倒地图,把频率相似的单词组合在一起呢?

解决方案二:使用Map<Integer, List<String>>

在我看来,这是一个更好的解决方案。此解决方案将对计数相似的所有单词进行分组。使用上述解决方案的相同输入,具有相似频率的单词将被捆绑在一起。因此,当查询最高计数的映射时,veryis都将按预期返回。使用Lambda表达式使得";反转";地图很容易:

Map<Integer, List<String>> mapInverted = 
wordCountMap.entrySet()
.stream()
.collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())));

System.out.println(mapInverted);

在将这些行添加到解决方案一的示例代码中之后,我现在有了一个类似字数的单词集合:

{1=[but, not, efficient, This, good, example], 2=[very, is]}

对于这两种方法,获得最大值的方法是:


Entry<String, Integer> maxEntry = Collections.max(wordCountMap.entrySet(),
(Entry<String, Integer> e1, Entry<String, Integer> e2) -> e1.getValue().compareTo(e2.getValue())); // for solution one
System.out.println(maxEntry); // outputs: very=2
Entry<Integer, List<String>> maxKey = Collections.max(mapInverted.entrySet(),
(Entry<Integer, List<String>> e1, Entry<Integer, List<String>> e2) -> e1.getKey().compareTo(e2.getKey())); // for solution two
System.out.println(maxKey); // outputs: 2=[very, is]

最新更新