387. First Unique Character in a String

9 篇文章 0 订阅
2 篇文章 0 订阅

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.

分别用了map,unorered_map,数组

1)map最费时,因为STL中的map的内部是用AVL树实现的,插入、查找、删除的时间复杂度都为O(lgN)。

2)unordered_map次之,boost中的unordered_map的内部使用散列表实现的,插入、查找、删除的时间复杂度为O(C)。

(c++11增加了unordered系列的容器(unordered_set、unordered_multiset、unordered_map、unordered_multimap),其原理是用hash做的,自然查找速度比原先的map和set要快很多。其实在C++11标准出来之前,基于hash的容器也已经有了,就是hash_map(在stdext或std::tr1内),只是正式标准出来之后,建议统一使用unordered系列的容器。)

虽然,unordered_map与hash_map都是用hash table实现的,但是unordered_map得性能更优一些。

(unordered_map属于关联式容器,采用std::pair保存key-value形式的数据。用法与map一致。特别的是,STL中的map因为是有序的二叉树存储,所以对key值需要有大小的判断,当使用内置类型时,无需重载operator < ;但是用用户自定义类型的话,就需要重载啦! unoredered_map全程使用不需要比较元素的key值的大小,但是,对于元素的==要有判断,又因为需要使用hash映射,所以,对于非内部类型,需要程序员为其定义这二者的内容,对于内部类型,就不需要了。

unordered库使用“桶”来存储元素,散列值相同的被存储在一个桶里。当散列容器中有大量数据时,同一个桶里的数据也会增多,造成访问冲突,降低性能。为了提高散列容器的性能,unordered库会在插入元素是自动增加桶的数量,不需要用户指定。但是,用户也可以在构造函数或者rehash()函数中,指定最小的桶的数量。)

hash table:


3)数组,也就是散列表,因为只有26个字母,不存在冲突的情况。所以插入、查找、删除的时间复杂度为O(1)。

代码:

class Solution {
public:
    int firstUniqChar(string s) {
        map<char, int> m;
        int i, ind = -1, size = s.size();
        for(i = 0; i < size; ++i) //整个插入的时间复杂度为O(lgN!)
            m[s[i]]++; 
        for(i = 0; i < size; ++i)//N*O(lgN)
            if(m[s[i]]==1){ 
                ind = i;
                break;
            }
        return ind;
        /*unordered_map<char, int> m;
        int i, ind = -1, size = s.size();
        for(i = 0; i < size; ++i) //整个插入的时间复杂度为O(C*N),C是常数,不一定是1 
            m[s[i]]++; 
        for(i = 0; i < size; ++i) //O(C*N)
            if(m[s[i]]==1){ 
                ind = i;
                break;
            }
        return ind;*/
        /*int m[26] = {0};
        int i, ind = -1, size = s.size();
        for(i = 0; i < size; ++i) //整个插入的时间复杂度为O(N)
            m[s[i]-'a']++;
        for(i = 0; i < size; ++i) //O(N)
            if(m[s[i]-'a']==1){
                ind = i;
                break;
            }
        return ind;*/
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值