[剑指offer] 50. 第一个只出现一次的字符 + map,hashmap 及其区别 C++ STL中哈希表 hash_map从头到尾详细介绍

class Solution {
public:
    int FirstNotRepeatingChar(string str) {
        map<char,int>mp;
        for(int i=0;i<str.size();i++){
            mp[str[i]]++;
        }
        for(int i=0;i<str.size();i++){
            if(mp[str[i]]==1)
                return i;
        }
        return -1;
    }
};

C++ Map常见用法说明: https://blog.csdn.net/shuzfan/article/details/53115922

C++ STL中哈希表 hash_map从头到尾详细介绍 : https://www.cnblogs.com/evidd/articles/8821349.html

一些简单用法:

int FirstNotRepeatingChar(string str) { 
    map<char, int> mp;  //遍历字符串,建立key:str[i] 和value: mp[str[i]]对应的map
    for (int i = 0; i < str.size(); ++i)     
        mp[str[i]]++;  

    map<char, int>::iterator it;//采用迭代器,循环输出mp
    it = mp.begin();   //可以看到str = "bgbddf";字符出现顺序是bgdf
    while (it != mp.end())  //map是基于红黑树构造的,会自动按字母序号重新排序,变成bdfg
    {
        cout << it->first<<' ';
        cout << it->second << endl;
        it++;
    }

    it = mp.find('d');//查找key
    if (it != mp.end())
        //mp.erase(it); // d被成功删除
        cout << mp['d']<< endl; //返回key对应的value, map不支持返回该元素的索引
    //mp中没有关键字1,使用[]取值会导致插入。 因此,该语句不会报错,会插入一对('\x1',0)。
    //同时由于数字的ASCII码小于字母,这个插入会被置于mp首位,而不是索引为1的位置。
    cout << mp[1] << endl; 


    for (int i = 0; i < str.size(); ++i){ //以ster.size()进行循环迭代,保证这里的字符顺序和原始str一致
        //cout << str[i] << " "<<mp[str[i]] << endl;
        if (mp[str[i]] == 1)   //返回第一个出现一次的字符的索引位置
            return i; 
    }        
    return -1; //不存在就返回-1
}

猜你喜欢

转载自www.cnblogs.com/nicetoseeyou/p/10677530.html