- 請實現一個函數用來找出字符流中第一個只出現一次的字符肃续。例如,當從字符流中只讀出前兩個字符"go"時话肖,第一個只出現一次的字符是"g"皇忿。當從該字符流中讀出前六個字符“google"時,第一個只出現一次的字符是"l"氓仲。
代碼如下:
public class AppearOnceInStream {
private int index;
private int[] count;
public AppearOnceInStream(){
count = new int[256];
for (int i=0;i<256;i++){
count[i] = -1;
}
}
public void Insert(char ch)
{
if (count[ch] == -1) count[ch] = index;
else if (count[ch] >= 0) count[ch] = -2;
index++;
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
//最大整數2的31次方-1
int minIndex = Integer.MAX_VALUE;
char c = '#';
for (int i=0;i<count.length;i++){
//每次循環(huán)滿足條件時水慨,為了保證第一次出現(字母順序靠前的不一定第一次出現),必須保證當前索引最小敬扛,小于記錄下的當前索引才可以重新賦值
if (count[i] >=0 && count[i] < minIndex){
minIndex = count[i];
c = (char)i;
}
}
return c;
}
public static void main(String[] args) {
AppearOnceInStream a = new AppearOnceInStream();
a.Insert('g');
a.Insert('o');
System.out.println(a.FirstAppearingOnce());
a.Insert('o');
a.Insert('g');
a.Insert('l');
a.Insert('e');
System.out.println(a.FirstAppearingOnce());
}
}