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

来源:互联网 发布:骰子软件 编辑:程序博客网 时间:2024/06/04 18:11

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:TextStatisticsMethod:averageLengthParameters:StringReturns:doubleMethod 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的同学能给出一个完善算法,我们共同交流共同进步~~~~~~~


原创粉丝点击