首页 > 学院 > 开发设计 > 正文

LeetCode 387. First Unique Character in a String

2019-11-11 05:17:45
字体:
来源:转载
供稿:网友

描述 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.

分析 考虑到题目中只有小写字母,可以采用桶计数的思路。

代码

class Solution {public: int firstUniqChar(string s) { int alpha[26] = {0}; const int n = s.size(); for (int i = 0; i < n; ++i) alpha[s[i] - 'a']++; for (int i = 0; i < n; ++i) if (alpha[s[i] - 'a'] == 1) return i; return -1; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表