MDGSF Software Engineer

[算法学习][leetcode] 387 First Unique Character in a String

2017-09-02
mdgsf
Art

https://leetcode.com/problems/first-unique-character-in-a-string/description/

题目

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.

题目翻译

题目解析

参考答案

#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
    int firstUniqChar(string s) {

        int aiANSI[128] = { 0 };

        for (char c : s)
        {
            aiANSI[c]++;
        }

        for (int i = 0; i < s.size(); i++)
        {
            if (aiANSI[s[i]] == 1)
            {
                return i;
            }
        }

        return -1;
    }
};

int main()
{
    Solution o;
    cout << o.firstUniqChar("loveleetcode") << endl;
    return 0;
}

weixingongzhonghao

Similar Posts

Comments