First Unique Character in a String

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: Using hash map

int firstUniqChar(string s) {
    unordered_map<char, int> m;
    for (auto ch: s) {
        m[ch] += 1;
    }

    for (int i=0; i<s.length(); i++) {
        if (m[s[i]] == 1) return i;
    }
    return -1;
}

Solution: Using array

    int firstUniqChar(string s) {
        int ascii[26] = {0};

        for (char ch : s) ascii[ch - '0'] += 1;
        for (int i = 0; i < s.size(); i++) {
            if (ascii[s[i] - '0'] == 1) return i;
        }
    }

Solution: Optimized using one loop

int firstUniqChar(string s) {
    int res = INT_MAX;
    int arr[26] = {0};
    for (int i=0; i<s.size(); i++) {
        if (arr[s[i]-'a']==0) {
            arr[s[i]-'a'] = i+1;  // avoid index 0
        } else{
           arr[s[i]-'a'] = -1; // repeat
        }
    }

    for(int i=0; i<26; i++) {
        if (arr[i] > 0 && arr[i] < res)
            res = arr[i];
    }

    return res == INT_MAX ? -1 : res-1;
}

results matching ""

    No results matching ""