题目内容
You would like to find the sentence containing the largest number of words in some given text. The text is specified as a string S consisting of N characters: letters, spaces, dots (.), question marks (?) and exclamation marks (!).The text can be divided into sentences by splitting it at dots, question marks and exclamation marks. A sentence can be divided into words by splitting it at spaces. A sentence without words is valid, but a valid word must contain at least one letter.For example, given S = "We test coders. Give us a try?", there are three sentences: "We test coders"," Give us a try" and "". The first sentence contains three words: "We", "test" and "coders". The second sentence contains four words: "Give", "us", "a" and "try". The third sentence is empty.Write a function:class Solution { public int solution(String $); }that, given a string S consisting of N characters, returns the maximum number of words in a sentence.For example, given S = "We test coders. Give us a try?", the function should return 4, as explained above.Given S="Forget CVs..Save time . x x", the function should return 2, as there are four sentences: "Forget CVs" (2 words), "" (0 words), "Save time "(2 words) and" x x" (2 words).Assume that:• the length of S is within the range [1..100];• string S consists only of letters (a-z, A-Z), spaces, dots (.), question marks (?) and exclamation marks (!).In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.
解法一
思路
先把文本字分句子。然后遍历每个句子分词,分词之后比较每个句子的中词的个数,最后返回最大的词的数量。
java代码实现
import java.util.ArrayList;
import java.util.List;
public class Task1 {private List divideIntoSentences(String text){List<String> sentences = new ArrayList<>();char[] chars = text.toCharArray();int startIndex = 0;int endIndex =0 ;for(int i=0; i<chars.length; i++){if ('.' == chars[i] || '!' == chars[i] || '?'==chars[i]){endIndex = i;sentences.add(text.substring(startIndex, endIndex));startIndex = endIndex+1;}}sentences.add(text.substring(startIndex-1, chars.length-1));return sentences;}public int solution(String text){if (text.length()==0){return 0;}List<String> sentences = divideIntoSentences(text);int maxLength = 0;int maxLengthInCurSentence;for (String sentence :sentences){maxLengthInCurSentence =0;String[] words = sentence.split(" ");for(int i=0; i< words.length; i++){if (words[i].length()!=0){maxLengthInCurSentence ++;}}if (maxLength < maxLengthInCurSentence){maxLength = maxLengthInCurSentence;}}return maxLength;}public static void main(String[] args) {Task1 task = new Task1();System.out.println(task.solution("We test coders. Give us a try?")); // Output: 4System.out.println(task.solution("Forget CVs..Save time . x x")); // Output: 2}}