【发布时间】:2019-06-13 08:03:24
【问题描述】:
给定一个字符串,找到其中第一个不重复的字符并返回它的索引。如果不存在,则返回 -1。
这个问题其实是我看了解决方案后才解决的。但我不明白 getCharOccur 函数中发生了什么。明确地,count[str.charAt(i)]++ 中究竟存储了什么。该数组中的索引和值是什么。同样在开始时,为什么我们将 count[] 声明为具有 256 个字符的空数组的动态数组?我尝试打印 count[str.charAt(i)]++ 但它在控制台中显示了一些空值。
public class Main {
static final int chars=256;
static char count[]=new char[chars];
//calculating the number of occurences of each character
static void getCharOccur(String str){
for(int i=0; i<str.length(); i++){
count[str.charAt(i)]++;
}
}
//Calculating index of first non repeating character
static int getNonRepeatChar(String str){
getCharOccur(str);
int index=-1;
for(int i=0; i<str.length(); i++){
if(count[str.charAt(i)]==1){
index=i;
break;
}
}
return index;
}
public static void main(String[] args) {
String str="thisisit";
int index=getNonRepeatChar(str);
System.out.println(index==-1 ? "Either all characters are
"repeating character is "+str.charAt(index));
}
}
打印出来的结果是有效的:第一个不重复的字符是 h
【问题讨论】:
-
你忘记发
getCharOccur()的代码了...
标签: java data-structures