您的位置:首页 > 其它

字符流中第一个不重复的字符

2016-03-09 15:42 197 查看
直接代码:

package TestProblem;

public class Test55 {
/**
* 题目:请实现一个函数用来找出字符流中第一个只出现一次的字符。
*/
private static class CharStatistics{
//出现一次的标识
private int index=0;
private int[] occurrence = new int[256];
public CharStatistics(){
for (int i = 0; i < occurrence.length; i++) {
occurrence[i]=-1; //默认初始全为-1
}
}
private void Insert(char ch){
if(ch>255){
throw new IllegalArgumentException(ch+"must be a ASCII char");
}
//只出现一次
if(occurrence[ch]==-1){
occurrence[ch]=index;//index记录字符串中的位置
}else{
//出现两次
occurrence[ch]=-2;
}
index++;
}
public char firstAppearingOnce(String data){
if (data == null) {
throw new IllegalArgumentException(data);
}
for (int i = 0; i < data.length(); i++) {
Insert(data.charAt(i));
}
//在对应的哈希表完了之后进行统计
char ch='\0';
//用于记录最小的索引,对应的就是第一个不重复的数字
int minIndex=Integer.MAX_VALUE;
for (int i = 0; i < occurrence.length; i++) {//遍历一遍数组
if(occurrence[i]>=0 &&occurrence[i]<minIndex){
ch=(char)i;
minIndex=occurrence[i];//找到最小的值主要是minIndex在不断的更新
}
}
return ch;
}
}
public static void main(String[] args) {
// System.out.println(new CharStatistics().firstAppearingOnce("")); // '\0'
// System.out.println(new CharStatistics().firstAppearingOnce("g")); // 'g'
// System.out.println(new CharStatistics().firstAppearingOnce("go")); // 'g'
// System.out.println(new CharStatistics().firstAppearingOnce("goo")); // 'g'
// System.out.println(new CharStatistics().firstAppearingOnce("goog")); // '\0'
// System.out.println(new CharStatistics().firstAppearingOnce("googl")); // l
System.out.println(new CharStatistics().firstAppearingOnce("google")); // l
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: