gpt4 book ai didi

java - 从段落中分离单词并插入到树结构中

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:30:43 26 4
gpt4 key购买 nike

我想创建一个用作单词计数器的程序。我打算使用树结构来存储单词。我还想计算单词的频率。我已经构建了二叉树和获取用户输入的方法。我应该怎么做?请帮忙。

这是我的代码。

public class Node {

int a;
String b;

Node leftChild;
Node rightChild;

Node(String b){
this.a = 0;
this.b = b;

this.leftChild = null;
this.rightChild = null;

}

public void display(){
System.out.println(" "+ b + " ");
}



public class Tree {

public Node root;

public Tree(){
root = null;
}


public void insert(String word){

Node newNode = new Node(word);
newNode.b = word;

if(root==null){
root = newNode;
}else{
Node current = root;
Node parent;

while(true){
parent = current;
if(word.compareToIgnoreCase(current.b)<0){

current = current.leftChild;

if(current == null){
parent.leftChild = newNode;
return;
}
}else{
current = current.rightChild;

if(current == null){
parent.rightChild = newNode;
return;
}
}
}

}






public Node search(String word){
Node current = root;

while(!current.b.equalsIgnoreCase(word)){

if(word.compareToIgnoreCase(current.b)<0){
current= current.leftChild;
}else{
current = current.rightChild;
}

if (current == null)
return null;
}
return current;
}


public void inOrder(Node localRoot){

if(localRoot != null){
inOrder(localRoot.leftChild);
localRoot.display();
inOrder(localRoot.rightChild);
}
}

这是主要方法。 (虽然它还没有接近完成)

import java.util.Scanner;

公共(public)课主要{

public static void main(String[] args) {

Tree newTree = new Tree();

Scanner inputString = new Scanner(System.in);

System.out.println("Type the paragraph and press \"Enter\" :");
String input = inputString.nextLine();

newTree.inOrder(newTree.root);


}

最佳答案

使用 map 或类似的东西来存储单词出现的次数会更容易。

但是如果你出于某种原因想使用树结构并且我正确理解你的问题,你应该修改你的插入方法:

//...
}else{
current = current.rightChild;

if(current == null){
parent.rightChild = newNode;
return;
} /*begin modification*/ else if (current.b.equalsIgnoreCase(word)) { // check if word already is stored in tree
++current.a; // increase counter
} /*end modification*/
}

现在您可以使用插入方法并计算同时添加的单词数。但请注意,由于 Node 构造函数中的 this.a = 0;,您的计数器目前从 0 开始。

然后在您的主要方法中,您可以将段落拆分为单词 (String[] words = input.split("");) 并使用 newTree 添加数组中的每个单词。 insert(words[i]); 在 for 循环中。

如果这不是您想知道的,您必须更清楚地说明您的问题。

关于java - 从段落中分离单词并插入到树结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16784657/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com