固定字符串的第一个不重复的字符
有关这个题目可以有很多的考察方式,但是本质的一个方法就是利用Hash表,来降低时间复杂度。
先看第一个题目,给定一个字符串,找到这个字符串的第一个不重复的字符:
在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符的位置。若为空串,返回-1。位置索引从0开始。
所以代码实现:
int FirstNotRepeatingChar(string str)
{
int hash_table[256] = {0};
if(str.empty())
{
return -1;
}
int len = str.size();
int i = 0;
for(i = 0; i < len; i++)
{
hash_table[str[i]]++;
}
for(i = 0; i < len; i++)
{
if(hash_table[str[i]] == 1)
return i;
}
if(i == len)
return -1;
}
流水字符串的第一个不重复的字符
算法:
字符流:像流水一样的字符,一去不复返,意味着只能访问一次。
方法1:将字符流保存起来
通过哈希表统计字符流中每个字符出现的次数,顺便将字符流保存在string中,然后再遍历string,从哈希表中找到第一个出现一次的字符;
方法2:哈希表特殊处理
同样通过哈希表来统计字符流中每个字符,不过不是统计次数,而是保存位置,哈希表初始化每个键值对应的value均为-1,如果字符出现一次,则value等于该字符的下标,如果字符出现两次,则value等于-2;这样遍历哈希表时,最小的那个非负值就是第一次不重复的字符的下标。
注意:这种方法是不需要保存流水的字符串的。
代码实现:
class Solution
{
public:
Solution() : index(0)
{
for(int i = 0; i < 256; ++i)
{
hash_table[i] = -1;
}
}
//Insert one char from stringstream
void Insert(char ch)
{
if(hash_table[ch] == -1)
{
hash_table[ch] = index;
}
else if(hash_table[ch] >= 0)
{
hash_table[ch] = -2;
}
++index;
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce()
{
char ch = '#';
int minIndex = index;
for(int i = 0; i < 256; i++)
{
if(hash_table[i] >= 0 && hash_table[i] < minIndex)
{
minIndex = hash_table[i];
ch = (char)i;
}
}
return ch;
}
private:
int hash_table[256];
int index;
};