- 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;
}
};
本文介绍了一种高效算法,用于在给定字符串中查找第一个不重复的字符,并返回其索引位置。通过使用字符计数表,算法能在遍历字符串两次的过程中找到目标字符,大大提高了查找效率。
1379

被折叠的 条评论
为什么被折叠?



