387. First Unique Character in a String

  • Total Accepted: 4516 
  • Total Submissions: 10603 
  • Difficulty: Easy

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) {
        map<char,int> mapping;
        vector<int>  record(26,0);
        bool flag=true;
        for(int i=0;i<s.size();i++)
            record[s[i]-'a']++;//统计每个单词出现次数
        for(int i=0;i<s.size();i++){
            if(record[s[i]-'a']==1)//找到首个出现次数为1的,找到了就返回其位置
                return i;
        }        
        return -1;        
    }
};

注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/52187799

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895

点赞