【问题标题】:Not able to understand the code to Count Duplicates in a string?无法理解计算字符串中重复项的代码?
【发布时间】:2021-03-06 00:22:00
【问题描述】:

此程序查找字符串中重复项的计数。


示例 1:

输入:

“阿布德”

输出:

2

说明:

“b”和“d”是两个重复项。


示例 2:

输入:

“eefggghii22”

输出:

3

说明:

重复项是“e”、“g”和“2”。


帮我看看这段代码。

public class CountingDuplicates {
  
  public static int duplicateCount(String str1) {
    // Write your code here
      int c = 0;
      str1 = str1.toLowerCase();
      final int MAX_CHARS = 256;
      int ctr[] = new int[MAX_CHARS];
      countCharacters(str1, ctr);
      for (int i = 0; i < MAX_CHARS; i++) {
        if(ctr[i] > 1) {
           // System.out.printf("%c  appears  %d  times\n", i,  ctr[i]);
           c = ctr[i];
        }
      }
      return c;
  }

  static void countCharacters(String str1, int[] ctr)
    {
       for (int i = 0; i < str1.length();  i++)
          ctr[str1.charAt(i)]++;
    }
}

【问题讨论】:

  • 嗯,那句话里有很多内容——你不明白其中的哪一部分?如果你把它分成int index = str1.charAt(i); ctr[index]++; 会帮助你理解它吗?

标签: java arrays string algorithm


【解决方案1】:

简而言之,它计算出现在字符串str 中的字符数并将其保存在ctr 数组中。

怎么样? ctr 是长度为 256 的数组。因此它可以有 256 个值(索引 0-255)。 str1 是包含字符串的字符串。 charAt(i) 方法返回索引 i 处的字符。因为 String 就像一个数组,您可以在其中访问每个 char 数组的索引值。

现在假设您的输入总是 ASCII 字符,每个 ASCII 字符包含一个 0-255 的值(即 ASCII 值“a”是 97)。 ++ 在任何变量之后意味着将其加 1。即c++ 表示c = c+1

现在进入循环ctr[str1.charAt(i)]++;,您可以看到循环从 0 开始,到字符串 str 的长度结束,其中 0 是第一个值 str。因此,如果字符串 str 的 0 索引值(第一个值)的值为 a,str.charAt(0) 将返回 97(实际上它会返回 'a' 但 java 采用 ASCII 值)。所以该行实际上是(对于第 0 个索引)ctr[97]++;,所以它将第 97 个索引(最初为 0)的值增加 1。所以现在该值为 1。

这样它只会增加与字符串中字符的ASCII值匹配的索引值,从而计算字符出现的时间。

【讨论】:

    【解决方案2】:

    您需要保持计数,如果该字符的值超过 1,则需要增加计数。

    返回该计数以了解重复的计数。

    添加了 cmets 以更好地理解代码。

    public class CountingDuplicates {
      
      public static int duplicateCount(String str1) {
        
        // Initialised integer to count the duplicates
          int count = 0;
        
        // Converting a string to lowercase to count lowerCase and Uppercase as duplicates
          str1 = str1.toLowerCase();
    
        // According to ASCII, the Maximum number of characters is 256, 
        // So, initialized an array of size 256 to maintain the count of those characters.
          final int MAX_CHARS = 256;
          int ctr[] = new int[MAX_CHARS];
    
          countCharacters(str1, ctr);
          for (int i = 0; i < MAX_CHARS; i++) {
            if(ctr[i] > 1) {
               // System.out.printf("%c  appears  %d  times\n", i,  ctr[i]);
               count = count + 1;
            }
          }
          return count;
      }
    
      static void countCharacters(String str1, int[] ctr)
        {
           for (int i = 0; i < str1.length();  i++)
              ctr[str1.charAt(i)]++;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-06
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多