剑指offer-34.第一个只出现一次的字符

题目:在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置。如果字符串为空,返回-1


思路:先在hash表中统计各字母出现次数,第二次扫描直接访问hash表获得次数


class Solution {
public:
    int FirstNotRepeatingChar(string str) 
    {
        if (str.size() == 0)
            return -1; //字符串为空,返回-1;
        int hash[256] = {0};
        int i = 0;
        while (str[i] != '\0')
        {
            hash[str[i]]++;
            i++;
        }
        i = 0;
        while (str[i] != '\0')
        {
            if (1 == hash[str[i]])
                return i;
            i++;
        }
        return -1;
        
    }
};


你可能感兴趣的:(剑指offer)