撰寫一個 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);
}
}
我想知道如何在不使用任何地圖或閱讀器的情況下列印這個詞。
我認為該程式將是一個非常復雜的程式,但我會理解的。
任何幫助將不勝感激。
uj5u.com熱心網友回復:
事實上,為了得到最頻繁的詞,現有的代碼需要稍微修改一下,只為最重復的變數提供一個變數,當檢測到更頻繁的詞時,必須更新該變數。此特定任務不需要額外的陣列/資料結構。
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;
}
}
uj5u.com熱心網友回復:
這是我使用 2 個陣列的解決方案:
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>或類似的東西來完成。
如果您被允許使用Maps 和流,那么這也可以(使用與上述相同的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
uj5u.com熱心網友回復:
有兩種解決方案,但一種比另一種更好。
解決方案一:使用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}
如您所見,very并且is與最常用的詞并列。這就是為什么這個解決方案不是最有效的。如果您可以反轉地圖以將具有相似頻率的單詞組合在一起怎么辦?
解決方案二:使用Map<Integer, List<String>>
在我看來,這是一個更好的解決方案。此解決方案將對具有相似計數的所有單詞進行分組。使用上述解決方案的相同輸入,具有相似頻率的單詞將被捆綁在一起。因此,在查詢地圖以獲取最高計數時,兩者very和is都將按預期回傳。使用 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]
uj5u.com熱心網友回復:
這是一種方法。它只是維護一個單詞串列,以便在遍歷串列時計算和調整最大值。
- 臨時陣列分配給最大字數。
cnt調整為根據發現的單詞控制通過更新的陣列的迭代。
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/421129.html
標籤:
上一篇:在Java中使用SimpleDateFormat將日期從一個更改為另一個
下一篇:如何在trie中考慮空格字符?
