count 是 char 数组,它只存储字符。
count[str.charAt(i)]++;
上面一行到底发生了什么?
count[str.charAt(i)] == 1
char array 的整数如何与 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));
}
}
至尊宝的传说
米脂
慕娘9325324
相关分类