First Unique Character in a String Solutions in C++
Number 387
Difficulty Easy
Acceptance 53.4%
Link LeetCode
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/first-unique-character-in-a-string/// Author : Hao Chen// Date : 2016-08-23class Solution {public:int firstUniqChar(string s) {//As the question mentioned, there only have lower case chars,//so the MAX_CHAR can be defined as 26, but I want this algorithm be more general for all ASCII#define MAX_CHAR 256#define NOT_FOUND -1#define DUPLICATION -2// initlize all chars status to NOT_FOUNDint pos_map[MAX_CHAR];memset(pos_map, NOT_FOUND,sizeof(pos_map));// if it is the first time to find, set the status to its postion// if it is the second time to find, set the status to duplication// if it has already duplicated, do nothingfor (int i=0; i<s.size(); i++){if ( pos_map[s[i]] >= 0 ) {pos_map[s[i]] = DUPLICATION;}else if ( pos_map[s[i]] == NOT_FOUND ) {pos_map[s[i]] = i;}}// find the lowest postionint pos = INT_MAX;for (auto item : pos_map) {cout << item << ",";if (item >= 0 && item < pos) {pos = item;}}return pos == INT_MAX ? -1 : pos;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/first-unique-character-in-a-string/description//// Author : liuyubobobo/// Time : 2017-10-16#include <iostream>using namespace std;/// Using Hash Map/// Time Complexity: O(len(s))/// Space Complexity: O(26)class Solution {public:int firstUniqChar(string s) {int freq[26] = {0};for(char c: s)freq[c-'a'] ++;for(int i = 0 ; i < s.size() ; i ++)if(freq[s[i]-'a'] == 1)return i;return -1;}};int main() {cout << Solution().firstUniqChar("leetcode") << endl;cout << Solution().firstUniqChar("loveleetcode") << endl;return 0;}