求第一个无重复字符,如"total"的第一个无重复字符是o,"teeter"的第一个无重复字符是r,效率要优于O(n的平方)
public static Character FirstNonRepeated(String)
下面是我把别人写的c程序翻译成java程序:
public class firstNonRepeatedChar {
private static final int MAX_CHAR = 256;
public static void main(String[] args) {
String str = "total";
firstNoRepeatedChar(str);
}
public static int firstNoRepeatedChar(String str) {
int i = 0;
int j = 0;
int[] p = new int[MAX_CHAR];
char[] chars = str.toCharArray();
//初始化数组p,p用于保存字符出现的次数
for (j = 0; j < MAX_CHAR; j++) {
p[j] = 0;
}
//统计字符出现的次数
for(i=0;i<chars.length;i++){
p[chars[i]]++;
}
//寻找第一个统计次数为1的字符
for (i = 0; chars[i] != -1; i++) {
if (p[chars[i]] == 1) {
System.out.println(chars[i]);
return 1;
}
}
return 0;
}
}
文章来源:
http://java999.blog.51cto.com/259217/162744