LeetCode 387. First Unique Character in a String 题解(C++)

来源:互联网 发布:ubuntu查看分区挂载点 编辑:程序博客网 时间:2024/06/05 04:09

LeetCode 387. First Unique Character in a String 题解(C++)


题目描述

  • Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.

举例

  • s = “leetcode”
    return 0.

    s = “loveleetcode”,
    return 2.

补充

  • You may assume the string contain only lowercase letters.

思路

  • 定义一个包含26个整数的数组cNum,用于保存每个字母出现的次数,遍历字符串s,将每个字母出现的次数记录在数组cNum里;
  • 再次遍历字符串,依照字符串的顺序检查每个字母是否只出现了一次,若该字母只出现了一次,则返回其位置;
  • 若遍历完成扔找不到位置,则证明不存在,返回-1。

代码

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