- First Position Unique Character
Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.
Example
Given s = “lintcode”, return 0.
Given s = “lovelintcode”, return 2.
代码如下:
class Solution {
public:
/**
* @param s: a string
* @return: it's index
*/
int firstUniqChar(string &s) {
int len = s.size();
if (len == 0) return -1;
vector<int> charTable(255, 0);
for (int i = 0; i < len; ++i) {
charTable[s[i]]++;
}
for (int i = 0; i < len; ++i) {
if (charTable[s[i]] == 1) return i;
}
return -1;
}
};