387. First Unique Character in a String

来源:互联网 发布:国家网络应急中心招聘 编辑:程序博客网 时间:2024/05/21 10:16

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.

Subscribe to see which companies asked this question.



找出字符串中第一个只出现一次的字母。题目说只出现小写字母。遍历字符串,用一个大小为26的数组计数。然后再遍历一次,遇到计数为1的就返回答案。


代码:

class Solution{public:int firstUniqChar(string s) {int cnt[26] = {0};for(auto c:s){cnt[c-'a']++;}for(int i = 0; i < s.size(); ++i){if(cnt[s[i]-'a'] == 1) return i;}return -1;}};


0 0
原创粉丝点击