stefans

frekventen string

Feb 10th, 2016
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class MostFrequentSubstring {
  4.  
  5. public static void main(String[] args) {
  6. Scanner std = new Scanner(System.in);
  7. String str = std.nextLine();
  8. HashMap<String, Integer> tabela = new HashMap<>();
  9. String search;
  10. for (int i = 0; i < str.length(); i++) {
  11. for (int j = i + 1; j <= str.length(); j++) {
  12. search = str.substring(i, j);
  13. if (tabela.containsKey(search)) {
  14. int g = tabela.get(search);
  15. tabela.put(search, ++g);
  16. } else
  17. tabela.put(search, 1);
  18. }
  19. }
  20. int max = 0;
  21. String maxSub = "";
  22. for (Map.Entry<String, Integer> entry : tabela.entrySet()) {
  23. if (entry.getValue() > max) {
  24. max = entry.getValue();
  25. maxSub = entry.getKey();
  26. } else if (entry.getValue() == max) {
  27. if (entry.getKey().length() > maxSub.length()) {
  28. maxSub = entry.getKey();
  29. } else if (entry.getKey().length() == maxSub.length()) {
  30. int n = 0;
  31. for (int i = 0; i < entry.getKey().length(); i++) {
  32. n += entry.getKey().charAt(i);
  33. }
  34. int m = 0;
  35. for (int i = 0; i < maxSub.length(); i++) {
  36. m += maxSub.charAt(i);
  37. }
  38. if (n < m)
  39. maxSub = entry.getKey();
  40. }
  41. }
  42. }
  43. System.out.println(maxSub);
  44. }
  45. }
Add Comment
Please, Sign In to add comment