hdu 单词数

单词数

Time Limit : 1000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 6   Accepted Submission(s) : 1
Problem Description
lily的好朋友xiaoou333最近很空,他想了一件没有什么意义的事情,就是统计一篇文章里不同单词的总数。下面你的任务是帮助xiaoou333解决这个问题。
 


 

Input
有多组数据,每组一行,每组就是一篇小文章。每篇小文章都是由小写字母和空格组成,没有标点符号,遇到#时表示输入结束。
 


 

Output
每组只输出一个整数,其单独成行,该整数代表一篇文章里不同单词的总数。
 


 

Sample Input
  
  
you are my friend #
 


 

Sample Output
  
  
4

 

 

方法一:字典树

import java.util.Scanner;

public class HduTest2 {
	
	public static Node root = null;
	public static int count = 0;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String str = "";
		while(sc.hasNextLine()) {
			str = sc.nextLine();
			if("#".equals(str)) {
				break;
			}
			root = new HduTest2().new Node();
			count = 0;
			String[] strArr = str.split("\\s+");//两个单词之间不一定是一个空格
			for(int i=0; i<strArr.length; i++) {
				if(strArr[i].length() != 0) {//注意1:如果每一行的最前面有空格,就会截出一个长度为0的字符串
					createTree(strArr[i]);
				}
			}
			System.out.println(count);
		}
	}
	
	private static void createTree(String str) {
		Node tempNode = root;
		int ch;
		for(int i=0; i<str.length(); i++) {
			ch = str.charAt(i)-'a';
			if(tempNode.arr[ch] == null) {
				tempNode.arr[ch] = new HduTest2().new Node();
			}
			tempNode = tempNode.arr[ch];
		}
		if(tempNode.end != true) {
			tempNode.end = true;
			count ++;
		}
	}

	class Node {
		Node[] arr = new Node[26];
		boolean end = false;
		
		public Node() {
			for(int i=0; i<26; i++) {
				arr[i] = null;
			}
		}
	}

}

 

方法二:集合法(简单,容易实现)

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class HduTest3 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String str = "";
		while(sc.hasNextLine()) {
			str = sc.nextLine();
			if("#".equals(str)) {
				break;
			}
			Set<String> set = new HashSet<String>();
			String strArr[] = str.split("\\s+");
			for(int i=0; i<strArr.length; i++) {
				if(strArr[i].length() != 0) {
					set.add(strArr[i]);
				}
			}
			System.out.println(set.size());
		}
	}
}



 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值