[leetcode]: 387. First Unique Character in a String

来源:互联网 发布:mac os 10.12.6 降级 编辑:程序博客网 时间:2024/06/06 02:56

1.题目描述

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.

2.分析

自己的做法是遍历两边,看了solution好像都差不多。
第一次遍历:计数,统计每个字符出现的次数。
第二次遍历:找第一个出现次数为1的字符的位置

3.代码

c++

int firstUniqChar(string s) {    int* hashTable = new int[26]();    for (char ch : s)        ++hashTable[ch - 'a'];    for (int i = 0; i < s.size(); i++)        if (hashTable[s[i] - 'a'] == 1)//第一个出现一次的字符            return i;    return -1;}
0 0