无法理解在字符串中计算重复项的代码? [英] Not able to understand the code to Count Duplicates in a string?

查看:56
本文介绍了无法理解在字符串中计算重复项的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该程序查找字符串中重复项的数量.

This program finds the count of duplicates in a string.

示例1:

输入:

"abbdde"

输出:

2

说明:

"b"和"d"表示是两个副本.

"b" and "d" are the two duplicates.

示例2:

输入:

"eefggghii22"

"eefggghii22"

输出:

3

说明:

重复项是"e","g"和"2".

duplicates are "e", "g", and "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)]++;
    }
}

推荐答案

简而言之,它是对出现在字符串 str 中的字符数进行计数并将其保存在 ctr 中数组.

In short it is counting the number of characters appearing in the String str and saving it in ctr array.

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

How? ctr is the array that has a length of 256. So it can have 256 values (0-255 indexed). str1 is the string that contains the String. charAt(i) method returns the character at index i. Because String acts like an array where you can access each char a index values of an array.

现在假设您的输入将始终为ASCII字符,则每个ASCII字符均包含0-255的值(即ASCII值"a"为97). ++ 在任何变量之后表示将1加.即 c ++ 表示 c = c + 1

Now assuming your input will always ASCII characters, each ASCII chars contain a value of 0-255 (i.e. ASCII value 'a' is 97). ++ after any variable means adding 1 to that. i.e.c++ means 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.

Now coming to the loop, ctr[str1.charAt(i)]++;, you can see the loops starts from 0 and ends at the length of the String str where 0 is the first value str. So if value of 0 indexed value (first value) of the String str is a, str.charAt(0) would return 97(well actually it will return 'a' but java takes the ASCII value). so the line actually is (for 0 th index) ctr[97]++; so it's incrementing the value of the 97th index (which is initially 0) by 1. So now the value is 1.

像这样,它将仅增加与字符串中字符的ASCII值匹配的索引值,从而计算字符出现的时间.

Like this way it will only increment the index values that matches with the ASCII values of the character in the String, thus counting the amount of time the characters occur.

这篇关于无法理解在字符串中计算重复项的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆