谁能解释一下代码中最先出现的for循环的过程。如果在控制台中打印这两行,则会得到输出[0 0 0 1 2]。我不知道“它是如何在幕后每次增加字符数的。”
for (int i=0; i<len; i++)
count[str.charAt(i)]++;
//Code
public class GFG
{
static final int ASCII_SIZE = 256;
static char getMaxOccuringChar(String str)
{
// Create array to keep the count of individual
// characters and initialize the array as 0
int count[] = new int[ASCII_SIZE];
// Construct character count array from the input
// string.
int len = str.length();
for (int i=0; i<len; i++) //bit confused lines
count[str.charAt(i)]++;
int max = -1; // Initialize max count
char result = ' '; // Initialize result
// Traversing through the string and maintaining
// the count of each character
for (int i = 0; i < len; i++) {
if (max < count[str.charAt(i)]) {
max = count[str.charAt(i)];
result = str.charAt(i);
}
}
return result;
}
// Driver Method
public static void main(String[] args)
{
String str = "abcaa";
System.out.println("Max occurring character is " +
getMaxOccuringChar(str));
}
}
for循环遍历字符串,str.charAt(i)
的值是索引str
处的i
字符。
str.charAt(i)
从str
的i
位置返回字符。 Char可以用作数组中的索引,例如myarray['c']
,因为'c'
可以表示为数字(请参见ASCII表)。