剑指offer 面试题50 第一个只出现一次的字符

问题1:在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).

输入:字符串

输出:第一个只出现一次的字符位置

思路:

创建一个数组,存放字符出现的次数

代码:

class Solution {
public:
    int FirstNotRepeatingChar(string str) {
        int len=str.size();
        if(len==0)
            return -1;
        vector<int> table(256,0);
        for(int i=0;i<len;++i)
            table[str[i]]++;
        for(int i=0;i<len;++i)
        {
            if(table[str[i]]==1)
                return i;
        }
        return -1;
    }
};

复杂度分析:时间复杂度为O(n),空间复杂度为O(1).


问题2:请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。

思路:

利用数组存放字符出现的index,出现两次时将值置为-2.

代码:

class Solution
{
public:
    Solution(): index(0)
    {
        for(auto i=0;i<256;++i)
            occurrence[i]=-1;
    }
    
  //Insert one char from stringstream
    void Insert(char ch)
    {
        if(occurrence[ch]==-1)
            occurrence[ch]=index;
        else if(occurrence[ch]>=0)
            occurrence[ch]=-2;
        index++;
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        char ch='#';
        int minIndex = INT_MAX;
        for(int i=0;i<256;++i)
        {
            if(occurrence[i]>=0&&occurrence[i]<minIndex)
            {
                ch=char(i);
                minIndex=occurrence[i];
            }
        }
        return ch;
    }
private:
    int occurrence[256];
    int index=0;
};

复杂度分析:插入时间复杂度为O(1),查找第一次出现的字符时间复杂度为O(1),空间复杂度为O(1).

发布了115 篇原创文章 · 获赞 14 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_22148493/article/details/105122737