for (char c : chars) { map.put(c, map.get(c) != null ? map.get(c) + 1 : 1); }
时间: 2024-05-22 20:12:37 浏览: 95
This code iterates through each character in an array called "chars". For each character, it checks if it already exists in a map (a data structure that maps keys to values). If it does, it gets the current value associated with the key (the character) and adds 1 to it. If it doesn't exist in the map, it adds the character to the map with a value of 1.
Overall, this code is counting the frequency of each character in the "chars" array and storing the results in a map.
相关问题
哈夫曼树以其编码解码\n要求:\n1.从终端读入字符集大小为n(即字符的个数),逐一输入n个字符和相应的n个权值(即字符出现的频度),建立哈夫曼树,进行编码并且输出。\n将它存于文件hfmtree中(选做)。\n2.利用已建好的哈夫曼编码文件hfmtree,对键盘输入的正文进行译码。输出字符正文,再输出该文的二进制码。\n[测试数据]\n用下表中给出的字符集(n=27)和频度的实际统计数据建立哈夫曼树:\n\n 并实现以下报文的译码和输出:“THIS PROGRAM IS MY FAVORITE”。java
以下是Java代码实现哈夫曼树的编解码:
```java
import java.io.*;
import java.util.*;
class HuffmanTree implements Serializable {
private static final long serialVersionUID = 1L;
private Node root;
private Map<Character, String> codeTable;
private class Node implements Comparable<Node>, Serializable {
private static final long serialVersionUID = 1L;
private char ch;
private int freq;
private Node left;
private Node right;
public Node(char ch, int freq, Node left, Node right) {
this.ch = ch;
this.freq = freq;
this.left = left;
this.right = right;
}
public boolean isLeaf() {
return left == null && right == null;
}
@Override
public int compareTo(Node other) {
return freq - other.freq;
}
}
public HuffmanTree(Map<Character, Integer> freqTable) {
PriorityQueue<Node> pq = new PriorityQueue<>();
for (char ch : freqTable.keySet()) {
pq.offer(new Node(ch, freqTable.get(ch), null, null));
}
while (pq.size() > 1) {
Node left = pq.poll();
Node right = pq.poll();
Node parent = new Node('\0', left.freq + right.freq, left, right);
pq.offer(parent);
}
root = pq.poll();
codeTable = new HashMap<>();
buildCodeTable(root, "");
}
private void buildCodeTable(Node node, String code) {
if (node.isLeaf()) {
codeTable.put(node.ch, code);
} else {
buildCodeTable(node.left, code + "0");
buildCodeTable(node.right, code + "1");
}
}
public void saveToFile(String filename) throws IOException {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
oos.writeObject(this);
}
}
public static HuffmanTree loadFromFile(String filename) throws IOException, ClassNotFoundException {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
return (HuffmanTree) ois.readObject();
}
}
public String encode(String plainText) {
StringBuilder encoded = new StringBuilder();
for (char ch : plainText.toCharArray()) {
encoded.append(codeTable.get(ch));
}
return encoded.toString();
}
public String decode(String encodedText) {
StringBuilder decoded = new StringBuilder();
Node node = root;
for (char c : encodedText.toCharArray()) {
if (c == '0') {
node = node.left;
} else {
node = node.right;
}
if (node.isLeaf()) {
decoded.append(node.ch);
node = root;
}
}
return decoded.toString();
}
}
public class HuffmanCoding {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Map<Character, Integer> freqTable = new HashMap<>();
freqTable.put('T', 2);
freqTable.put('H', 2);
freqTable.put('I', 2);
freqTable.put('S', 2);
freqTable.put('P', 1);
freqTable.put('R', 2);
freqTable.put('O', 1);
freqTable.put('G', 1);
freqTable.put('A', 1);
freqTable.put('M', 1);
freqTable.put('Y', 1);
freqTable.put('F', 1);
HuffmanTree huffmanTree = new HuffmanTree(freqTable);
huffmanTree.saveToFile("hfmtree");
// Test encoding and decoding
String plainText = "THIS PROGRAM IS MY FAVORITE";
String encodedText = huffmanTree.encode(plainText);
System.out.println("Encoded text: " + encodedText);
HuffmanTree huffmanTree2 = HuffmanTree.loadFromFile("hfmtree");
String decodedText = huffmanTree2.decode(encodedText);
System.out.println("Decoded text: " + decodedText);
System.out.println("Encoded binary: " + Arrays.toString(encodedText.chars().mapToObj(c -> (char) c).map(c -> huffmanTree.codeTable.get(c)).toArray()));
}
}
```
:利用键盘录入,输入一个字符串,统计该字符串中各个字符的数量,如用户输入字符串: "hello world java",程序输出结果:h(1)e(1)l(3)o(2) (2)w(1)r(1)d(1) j(1)a(2)v(1)。 (1)在窗体中添加JTextField组件用于输入一个字符串 (2)添加一个命令按钮,命令按钮完成如下功能: (3)将JTextField组件中的字符串保存在一个String对象中。 (4)将该字符串转换成字符数组 (5)创建map集合,用来存放字符:key是字符 value是字符出现的个数 (6)遍历字符数组 (7)拿到每个字符,去map中查看是否有保存对应的次数 (8)如果这个字符没有保存次数,就设置为1次 (9)如果这个字符有保存次数,就设置为原来的次数+1次 (10)按题目要求拼接字符串 (11)输出结果
下面是实现该功能的Java代码:
```java
import java.util.HashMap;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CharCount extends JFrame implements ActionListener {
private JTextField textField;
private JButton button;
private Map<Character, Integer> charCountMap;
public CharCount() {
super("字符统计");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new JLabel("请输入字符串:"));
textField = new JTextField(20);
add(textField);
button = new JButton("统计");
button.addActionListener(this);
add(button);
charCountMap = new HashMap<>();
pack();
setLocationRelativeTo(null); // 居中显示
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
String str = textField.getText();
char[] chars = str.toCharArray();
for (char c : chars) {
Integer count = charCountMap.get(c);
if (count == null) {
count = 1;
} else {
count += 1;
}
charCountMap.put(c, count);
}
StringBuilder result = new StringBuilder();
for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
result.append(entry.getKey());
result.append("(");
result.append(entry.getValue());
result.append(")");
}
System.out.println(result);
}
}
public static void main(String[] args) {
new CharCount();
}
}
```
运行该程序,输入字符串后点击“统计”按钮,程序会输出结果。注意每次统计前要清空map,否则上一次的结果会影响下一次的结果。
阅读全文