leetcode 字符串中的第一个唯一字符 C++

时间复杂度为O(n^2)的解法。

class Solution {
public:
    int firstUniqChar(string s) {
       // string temp;
        int num = 0;
        if(s.length() == 1)
        {
            return 0;
        }
        for(int i = 0;i<s.length();i++)
        {
            num = 0;
           //  temp = s.substr(i,1);
             for(int j = 0;j<s.length();j++)
             {
                 if(s[i] == s[j])
                     num ++;
                 if(num > 1)
                   break;  
                 if(j == s.length()-1)
                 {
                     return s.find(s[i]);
                 }
             }
        }
        return -1;
    }
};

上述做法并不适用于面试,接下来是时间复杂度为O(n) 的解法:

class Solution {
public:
    int firstUniqChar(string s) {
        if(s.empty()) return -1;
        if(s.length() == 1) return -0;
        const int tableSize = 256;
        unsigned int hashTable[tableSize];
        for(unsigned int i = 0;i<tableSize;++i)
            hashTable[i] = 0;
        
        char* pHashKey = &s[0];
        while(*(pHashKey) != '\0')
            hashTable[*(pHashKey++)] ++;
        pHashKey = &s[0];
        while(*pHashKey != '\0')
        {
            if(hashTable[*pHashKey] == 1)
                return s.find(*pHashKey);
            pHashKey++;
        }
        return -1;
    }
};

事实上,前者花费时间64ms,后者花费时间32ms。
后者是用到了一个哈希表,创建一个长度为256(char类型最大)的数组,每个字母根据其ASCII码值作为数组的下标对应数组的一个数字,而数组中存储的是每个字符出现的次数。此解法出自《剑指offer》。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值