fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. /* Find longest word in string */
  6. class Ideone {
  7.  
  8. private static List<String> findLongestWords(String txt) {
  9. int idx = 0;
  10. List<String> words = new ArrayList<>();
  11. int longest = 0;
  12.  
  13. while (idx < txt.length()) {
  14. int start = idx;
  15. while (start < txt.length() && txt.charAt(start) == ' ') {
  16. start++;
  17. }
  18.  
  19. idx = start;
  20. while (idx < txt.length() && txt.charAt(idx) != ' ') {
  21. idx++;
  22. }
  23.  
  24. int len = idx - start;
  25. String word = txt.substring(start, idx);
  26.  
  27. if (len > longest) {
  28. longest = len;
  29. words = new ArrayList<>();
  30. words.add(word);
  31. } else if ((len == longest) && (len > 0)) {
  32. words.add(word);
  33. }
  34. }
  35. return words;
  36. }
  37.  
  38. public static void main(String[] args) throws java.lang.Exception {
  39. Scanner sc = new Scanner(System.in);
  40. while (sc.hasNextLine()) {
  41. String line = sc.nextLine();
  42. List<String> words = findLongestWords(line);
  43. System.out.printf("Longest: /%s/%n", words);
  44. }
  45. }
  46. }
  47.  
  48.  
  49.  
Success #stdin #stdout 0.07s 4386816KB
stdin
Ala ma kota a kot ma hive
Ala 
 Ala
Alamo
   
 
A
stdout
Longest: /[]/
Longest: /[kota, hive]/
Longest: /[Ala]/
Longest: /[Ala]/
Longest: /[Alamo]/
Longest: /[]/
Longest: /[]/
Longest: /[A]/