时间复杂度为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》。