387. First Unique Character in a String
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
相关链接如下:
知乎:littledy
GitHub主页:https://github.com/littledy
github.io:https://littledy.github.io/
欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可
作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。