gpt4 book ai didi

java - 计数数组的行为

转载 作者:行者123 更新时间:2023-12-02 02:44:06 25 4
gpt4 key购买 nike

count 是字符数组,它只存储字符。

count[str.charAt(i)]++;

上面一行到底发生了什么?

count[str.charAt(i)] == 1

整数如何与 char 进行比较作为计数是 char 数组?

下面粘贴的代码用于找出字符串中的第一个非重复字符。它绝对有效。

谁能回答我上面提到的两个问题吗?

class GFG { 
static final int NO_OF_CHARS = 256;
static char count[] = new char[NO_OF_CHARS];

/* calculate count of characters
in the passed string */
static void getCharCountArray(String str)
{
for (int i = 0; i < str.length(); i++)
{ //System.out.println(count[str.charAt(i)]+" Before");
count[str.charAt(i)]++;
// System.out.println(count[str.charAt(i)]+" After");
}
}

/* The method returns index of first non-repeating
character in a string. If all characters are repeating
then returns -1 */
static int firstNonRepeating(String str)
{
getCharCountArray(str);
int index = -1, i;

for (i = 0; i < str.length(); i++)
{
if (count[str.charAt(i)] == 1)
{
index = i;
break;
}
}

return index;
}

// Driver method
public static void main (String[] args)
{
String str = "geeksforgeeks";
int index = firstNonRepeating(str);

System.out.println(index == -1 ? "Either all characters are repeating or string " +
"is empty" : "First non-repeating character is " + str.charAt(index));
}

}

最佳答案

根据 Oracle 文档:

The char data type is a single 16-bit Unicode character. It has a minimum value of > >'\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

为此,您可以将其视为 16 位无符号(即正)整数。因此,由于 Java 类型之间的自动转换,代码 char c = 1; 等效于 char c = (int) 1;。这与 long l = 1; 类似,尽管 1 是一个整数原语,因为 Java 语言理解您可能想要一个 long而不是 int

因此,count[i] == 1 的行为与您将 is 定义为 int[] 完全相同,并检查该处字节的数值索引以查看它们是否等于1

如果您尝试检查该索引是否包含字符 1,则可以尝试 count[i] == '1'; (注意单引号,用于字 rune 字而不是字符串文字)。

关于java - 计数数组的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57158968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com