首页 文章

如何使用嵌套循环计算字符串中重复字符的总数?

提问于
浏览
1

我需要编写一个程序来计算String中重复字符的总数 . 例如,如果字符串是“gigi the gato”,则输出为7.('g'重复3次'i'重复2次't'重复两次 . )我需要使用嵌套循环 .

这就是我所拥有的 . 这个想法是正确的,但我的输出5是错误的 .

public class CountD {
    public static void main(String[] args) {
        String s1 = "gigi the gato";
        s1 = s1.replace(" ", "");
        int count = 0;
        for (int i = 0; i < s1.length(); i++) {
            for (int j = i + 1; j < s1.length(); j++) {
                if (s1.charAt(i) == s1.charAt(j)) {
                    count++;
                }
            }
        }
        System.out.println(count);
    }
}

问题是这个代码计算每个char重复的次数(如果它这样做)但它不包括char本身 . 其次,如果char重复两次以上,则每次出现后都会对此char进行额外计数 . 对不起,如果它令人困惑 . 无论如何,您可以自己跟踪代码 . 你能解决它并解释你是怎么做的吗?

5 回答

  • 1

    是否真的有必要使用嵌套循环?你可以试试这个:

    public static void main(String[] args) {
      String s1 = "gigi the gato";
      s1 = s1.replaceAll(" ", "");
      int count = 0;
      while (s1.length() > 0) {
        int lengthBefore = s1.length();
        String firstChar = s1.substring(0, 1);
        s1 = s1.replace(firstChar, "");
        int diff = lengthBefore - s1.length();
        if (diff > 1) count += diff;
      }
      System.out.println(count);
    }
    
  • 0

    如果您被允许使用流媒体:

    import static java.util.stream.Collectors.counting;
    import static java.util.stream.Collectors.groupingBy;
    
    public static long countD(String s) {
        Map<Integer, Long> map = s.chars()
                .filter(c -> c != ' ').boxed()
                .collect(groupingBy(c -> c, counting()));
    
        return map.values().stream()
                .filter(count -> count > 1)
                .mapToLong(c -> c)
                .sum();
    }
    
    
      public static void main(String[] args) {
            System.err.println(countD("gigi the gato")); // 7
            System.err.println(countD("gigi tge gato")); // 8
      }
    
  • 0

    使用外部 for 循环遍历相同的字符串,将计算已经一次又一次计数的相同字符 .
    while 循环替换外部 for 循环,并在每次char检查后,从字符串中删除char:

    public static void main(String[] args) {
        String s1 = "gigi the gato";
        s1 = s1.replace(" ", "");
        int count = 0;
        while (!s1.isEmpty()) {
            boolean found = false;
            for (int j = 1; j < s1.length(); j++) {
                if (s1.charAt(0) == s1.charAt(j)) {
                    found = true;
                    count++;
                }
            }
            if (found)
                count++;
            s1 = s1.replace(s1.substring(0, 1), "");
        }
        System.out.println(count);
    }
    
  • 0

    匹配时设置标志 . 一旦内部循环完成,基于标志增加计数 . 这可确保包含原始字符数 .

  • 0
    public static int countDuplicatedChars(String str) {
        int count = 0;
        char[] arr = str.toLowerCase().toCharArray();
    
        for (int i = 0; i < arr.length; i++) {
            char ch = arr[i];
    
            if (ch == ' ' || ch == '\0')
                continue;
    
            int total = 0;
    
            for (int j = i; j < arr.length; j++) {
                if (ch != arr[j])
                    continue;
                total++;
                arr[j] = '\0';
            }
    
            if (total > 1)
                count += total;
        }
    
        return count;
    }
    

    您可以使用 Stream 执行相同的操作:

    public static int countDuplicatedChars(String str) {
        return str.chars()
                  .filter(ch -> ch != ' ')
                  .mapToObj(i -> (char)i)
                  .collect(Collectors.groupingBy(Function.identity(), Collectors.collectingAndThen(Collectors.counting(), Long::intValue)))
                  .entrySet().stream()
                  .mapToInt(Map.Entry::getValue)
                  .filter(count -> count > 1)
                  .sum();
    }
    

相关问题