剑指offer:第一个只出现一次的字符

题目描述:

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

思路:

以空间换时间。遍历一次数组,用一个256大小的hash数组存储下所有字母出现次数(下标是字母的ASCII码),再遍历一次找到第一个次数为1的数输出下标。

大小设为256是因为字母的ASCII最大到255。

使用unordered_map也可以,字符对应出现次数的映射,这里没有必要,用数组就可以完成。

参考代码:

在线测试

https://www.nowcoder.com/practice/1c82e8cf713b4bbeb2a5b31cf5b0417c?tpId=13&tqId=11187&rp=2&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&tPage=2

AC代码

class Solution {
public:
    int FirstNotRepeatingChar(string str) {
        if(str.empty())
            return -1;
        int hash[256]={0};
        //unordered_map<char,int> hash;
        for(int i=0;i<str.size();i++)
        {
            hash[str[i]]++;
        }
        for(int i=0;i<str.size();i++)
        {
            if(hash[str[i]]==1)
                return i;
        }
        return -1;
    }
};

猜你喜欢

转载自blog.csdn.net/u012991043/article/details/81489596
今日推荐