fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5. Scanner sc = new Scanner(System.in);
  6. int n = sc.nextInt();
  7. String s = sc.next();
  8.  
  9. System.out.println(findMaxPartitions(s, n));
  10. }
  11.  
  12. public static int findMaxPartitions(String s, int n) {
  13. for (int len = 1; len <= n; len++) {
  14. if (n % len != 0) continue; // 子串长度必须能整除整个字符串的长度
  15. if (canBePartitioned(s, len)) {
  16. return n / len;
  17. }
  18. }
  19. return 1;
  20. }
  21.  
  22. private static boolean canBePartitioned(String s, int len) {
  23. String[] substrings = new String[s.length() / len];
  24. for (int i = 0; i < s.length(); i += len) {
  25. substrings[i / len] = s.substring(i, i + len);
  26. }
  27.  
  28. // 检查所有子串是否可以通过交换变成相同的内容
  29. Map<Character, Integer> baseFrequency = getFrequency(substrings[0]);
  30. for (int i = 1; i < substrings.length; i++) {
  31. if (!baseFrequency.equals(getFrequency(substrings[i]))) {
  32. return false;
  33. }
  34. }
  35. return true;
  36. }
  37.  
  38. private static Map<Character, Integer> getFrequency(String str) {
  39. Map<Character, Integer> frequencyMap = new HashMap<>();
  40. for (char c : str.toCharArray()) {
  41. frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1);
  42. }
  43. return frequencyMap;
  44. }
  45. }
  46.  
Success #stdin #stdout 0.12s 56764KB
stdin
8
01102222
stdout
1