LeetCode387. First Unique Character in a String

原创 2016年08月28日 23:40:55

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 num[26] = {0};
        int pos[26] = {0};
        for (int i = 0; i < s.size(); i++) {
            char c = s[i];
            num[c-'a']++;
            pos[c-'a'] = i;
        }
        int i = 0;
        int idx = s.size();
        while (i < 26)
        {
            if (num[i] == 1) {
                if (pos[i] < idx) idx = pos[i];
            }
            i++;
        }
        if (idx == s.size())
            idx = -1;
        return idx;
    }
};



版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode 387. First Unique Character in a String 解题报告

LeetCode 387. First Unique Character in a String 解题报告

LeetCode-387. First Unique Character in a String (Java)

Given a string, find the first non-repeating character in it and return it's index. If it doesn't ex...
  • NOadu
  • NOadu
  • 2017年06月25日 09:58
  • 208

LeetCode之路:387. First Unique Character in a String

LeetCode之路:387. First Unique Character in a String 一、引言这道题题意非常简单,却让我思考了很久,或许难的并不是这道题,是纠结于解题思路的那种困扰吧。...

leetcode.387. First Unique Character in a String--字符串首个不重复的字母

Given a string, find the first non-repeating character in it and return it's index. If it doesn't ex...

LeetCode笔记:387. First Unique Character in a String

找到一个字符串中第一个只出现一次的字母

Leetcode 387. First Unique Character in a String 第一个唯一字符 解题报告

1 解题思想这题的意思是,给一个字符串,找出第一个只出现一次的字符的位置。这道题限定了只有小写字符,所以用一个小写字符的数组去做标志位,记录某个字符是否出现,如果出现了一次那么位置在哪里,或者出现了多...
  • MebiuW
  • MebiuW
  • 2016年08月24日 13:02
  • 1303

关于LeetCode中First Unique Character in a String一题的理解

题目如下: Given a string, find the first non-repeating character in it and return it's index. If it do...

LeetCode - First Unique Character in a String

题目 Given a string, find the first non-repeating character in it and return it’s index. If it doesn’...

leetcode:Unique Substrings in Wraparound String

Consider the string s to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so s wi...

LeetCode 题解(Week 10): 467. Unique Substrings in Wraparound String

原题目Consider the string s to be the infinite wraparound string of “abcdefghijklmnopqrstuvwxyz”, so s ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode387. First Unique Character in a String
举报原因:
原因补充:

(最多只允许输入30个字)