Problem:
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
Note: You may assume the string contain only lowercase letters.
思路:
Solution (C++):
int firstUniqChar(string s) {
int n = s.length(), i, j;
if (n == 0) return -1;
if (n == 1) return 0;
set<char> st;
for (i = 0; i < n-1; ++i) {
if (st.find(s[i]) != st.end()) continue;
else st.insert(s[i]);
for (j = i+1; j < n; ++j) {
if (s[i] == s[j]) break;
}
if (j == n) return i;
}
if (st.find(s[n-1]) == st.end()) return n-1;
return -1;
}
性能:
Runtime: 80 ms Memory Usage: 10.9 MB
思路:
Solution (C++):
性能:
Runtime: ms Memory Usage: MB