diff --git a/solution/387.First Unique Character in a String/Solution.cpp b/solution/387.First Unique Character in a String/Solution.cpp new file mode 100644 index 0000000000000..fc930c5a08560 --- /dev/null +++ b/solution/387.First Unique Character in a String/Solution.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int firstUniqChar(string s) { + vector cnts(26, 0), pos(26, s.size()) ; + + + for (int i = s.size()-1; i >= 0; --i) + { + int index = s[i] - 'a' ; + cnts[index]++ ; + pos[index] = i ; + } + + int p = s.size() ; + for (int i = 0; i < 26; ++i) + { + if (cnts[i] == 1 && pos[i] < p) + p = pos[i] ; + } + + return p != s.size()? p: -1 ; + } +}; \ No newline at end of file