JAVA学习日记----------

JAVA学习日记----------

今天仅有TopCoder例题更新

Problem Statement

 

Most modern text editors are able to give some statistics about the text they are editing. One nice statistic is the average word length in the text.

A word is a maximal continuous sequence of letters ('a'-'z', 'A'-'Z'). Words can be separated by spaces, digits, and punctuation marks.

The average word length is the sum of all the words' lengths divided by the total number of words. For example, in the text "This is div2 easy problem.", there are 5 words: "This", "is", "div", "easy", and "problem". The sum of the word lengths is 4+2+3+4+7=20, so the average word length is 20/5=4.

Given a String text, return the average word length in it. If there are no words in the text, return 0.0.

Definition

 
Class:TextStatistics
Method:averageLength
Parameters:String
Returns:double
Method signature:double averageLength(String text)
(be sure your method is public)

算法如下:

public class TextStatistics {


public double averageLength(String text) {
double count = 0;
int sum = 0;
String[] strList = text.split("[0-9 ,.?!-]+");
for (String str : strList) {
sum = sum + str.length();
}
if(strList.length!=0){
count = sum / strList.length;
return count;
}
return 0;
}
}

今天学习到的东西:

1. 上面算法可以将给出的字符串按照单词分割,举个例子:“This0 is1 a2 test3 text4?”通过算法后,变为“This”,“is”,“a”,“test”,"text", 但是算法有问题这个测试用例就是错误的“!This0 is1 a2 test3 text4?”

2.正则表达式"[0-9 ,.?!-]+"表示多次匹配数字0到9,空格,逗号,句号,问号,叹号,破折号。


P.S.另外请看到这篇Blog的同学能给出一个完善算法,我们共同交流共同进步~~~~~~~


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值