CountWord
unknown
java
4 years ago
2.1 kB
10
Indexable
package DSA_20020153_DoanThanhSon.week8;
import edu.princeton.cs.algs4.MinPQ;
import java.io.*;
import java.util.*;
import java.util.regex.Pattern;
public class CountWord {
public void count(String input) {
input = input.replaceAll(Pattern.quote(",") , "");
input = input.replaceAll(Pattern.quote("."), "");
String[] words = input.split(Pattern.quote(" "));
// useTreeMap(words);
// useRedBlackTree(words);
useMinPQ(words);
}
public void useTreeMap(String[] words){
Map<String, Integer> map = new TreeMap<>();
for (String word : words) {
if (!map.containsKey(word)) {
map.put(word,1);
} else {
map.put(word, map.get(word) + 1);
}
}
for (var entry : map.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
public void useRedBlackTree(String[] words) {
RedBlackTree redBlackTree = new RedBlackTree();
for (String word : words) {
redBlackTree.insert(word);
}
redBlackTree.printTree();
}
public void useMinPQ(String[] words) {
MinPQ<String> minPQ = new MinPQ<>();
for (String word: words) {
minPQ.insert(word);
}
String previous = minPQ.delMin();
int num = 1;
String current;
while (!minPQ.isEmpty()) {
current = minPQ.delMin();
if (!current.equals(previous)) {
System.out.println(previous + " " + num);
num = 1;
previous = current;
} else {
num++;
}
}
System.out.println(previous + " " + num);
}
public static void main(String[] args) throws IOException {
File f = new File("D:\\Java Project\\DSA\\src\\DSA_20020153_DoanThanhSon\\week8\\word_data.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
String input = br.readLine();
CountWord countWord = new CountWord();
countWord.count(input);
}
}Editor is loading...