Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

You would like to find the sentence containing the largest number of words in so

ID: 3839649 • Letter: Y

Question

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 s);} 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)

Explanation / Answer

class Solution {

public int solution(String s){

StringTokenizer st= new StringTokenizer(s);
       String res = new String();
       StringBuilder k= new StringBuilder();
       HashMap<Integer, Integer> hp= new HashMap<Integer, Integer>();
       Integer i=1;
       Integer cnt=0;
       while(st.hasMoreTokens()){
           res= st.nextToken();
           if(res.contains(".") || res.contains("?") || res.contains(",")){
               k.append(res);
               cnt++;
               k.setLength(0);
               hp.put(i, cnt);
               cnt=0;
               i++;
              
           }
           else{
               k.append(res);
               cnt++;
           }
          
       }
       Integer c=0;
       for(Integer a=1; a<i;a++){
           if(hp.get(a)>c){
               c=hp.get(a);
           }
       }
return(c);

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote