Title: In a string (0 <= length of the string <= 10000, all of the alphabet) find a first character appears only once, and returns to its position, or -1 if not (case sensitive ).
ideas: the first time through the string with a hash table to count the number of each character appears, the second pass the string, when the number of occurrences is 1, output index, no, the output -1
class Solution {
public:
int FirstNotRepeatingChar(string str) {
map<char,int> m;
for(int i= 0;i<str.size();++i)
++m[str[i]];
for(int i=0;i<str.size();++i)
{
if(m[str[i]]==1)
return i;
}
return -1;
}
};
python solution:
class Solution:
def FirstNotRepeatingChar(self, s):
m = {}
for ch in s:
if ch in m:
m[ch] = m[ch] +1
else:
m[ch] =1
for i in range(len(s)):
if m[s[i]] == 1:
return i
return -1