洛谷P1308 统计单词数 的Java实现

题目来源

P1308 (NOIP2011 普及组)统计单词数

AC代码

import java.util.ArrayList;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan = new Scanner(System.in);
		String str1 = scan.nextLine();
		String str2 = scan.nextLine();
		String[] data = str2.trim().split("\\s+");
		char[] data1 = str2.toCharArray(); 
		ArrayList<Integer> arr = new ArrayList<Integer>();
		int index= 0;
		int time = 0;
		int count = 0;
		int sum = 0;
		//arr表示每个在data位置的单次前面有多少个空格
		//判断第一个单次前面是否有空格
		if(data1[0] != ' ')
			arr.add(0);
		for(int i=0;i<data1.length;i++) {
			if(data1[i] == ' ') {
				count++;
			}
			else {
				if(count != 0) {
			        arr.add(count);
			        count = 0;
			       }
			}
		}
		for(int i =  0 ; i < data.length ; i++) {
			if(data[i].equalsIgnoreCase(str1)) {
				time ++;
				if(time == 1) {
					index = sum;
					for(int j = 0; j <= i;j++) {
						index += arr.get(j);
					}
				}
			}
			sum += data[i].length();
		}
		if(time == 0)
			System.out.println(-1);
		else
			System.out.println(time+" "+index);
		scan.close();
	}
}

个人总结与思考

  1. 这道题考察的点在字符串分割。我们要明白每个单词之间都会有不定长度的空格,首个单词前面也会有空格。所以我先用了以下代码对不定长度的空格为依据来分割字符串:
String[] data = str2.trim().split("\\s+");

为了获得我们要的单词,我们要用trim方法去掉句子前的空格,如果不用trim方法会在数组第一个位置分割出一个空格来。

  1. 第二个考察点是计算出有多少每个字符串之前有多少个空格,字符的长度我们用Java String 类自带的方法就可以得到。所以我用以下代码,将String按照每个位置的字符转换为char类型,并计算出每个非空字符前的空格数量:
if(data1[0] != ' ')
	arr.add(0);
for(int i=0;i<data1.length;i++) {
	if(data1[i] == ' ') {
			count++;
		}
	else {
		if(count != 0) {
			  arr.add(count);
			  count = 0;
			     }
			}
		}

难点在于句子第一个字母前可能有空格,也可能没有空格。

  1. 我学习了其它人的代码,发现直接用split方法分割空格就行,我做的虽然更加细致但是有点多此一举了,我们不用计算空格的个数这么麻烦;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TerryBlog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值