知识点/数据结构:字符串
题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
思路:
写在了代码中。利用变量做标记,很棒的办法。学习!!!!
public class Solution {
//因为字符的ASIC码范围是0-255.定义长度为256的数组。
int count[] = new int[256];
//Insert one char from stringstream
int index=1;
public void Insert(char ch)
{
//char类型会自动转换为int类型,向高等级类型自动完成,向低等级的则需要强制符号。转换后的int对应0-256.
//如果==0表示,第一次出现这个字母,因为初始化的时候数组中元素为默认值0。
if(count[ch]==0){
count[ch]=index++;
}
else{
//这里表示不是第一次出现。
count[ch]=-1;
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
//Integer.MAX_VALUE,即2147483647
//第一次比较的时候需要用到的初始值。就是一个字符可能出现了多少次
int temp=Integer.MAX_VALUE;
char ch='#';
for(int i=0;i<256;i++){
//不等于0是出现过;不等于-1是只出现了一次
//明白了! temp=count[i];
//count[i]<temp 目的就是为了遍历所有的后确定index最小的那个
//上面的index标注了每个字符出现的顺序
if(count[i]!=0&&count[i]!=-1&&count[i]<temp){
temp=count[i];
//类型强制转换
ch=(char)i;
}
}
return ch;
}
}