<剑指Offer>面试题50(1): 字符串中第一个只出现一次的字符

题目描述

  • 在字符串中找出第一个只出现一次的字符
  • 如,输入 "abaccdeff",则输出 b

题目解读

  • 剑指Offer 243

代码

  • 思路一,直接使用STL中的map
#include
#include
using namespace std;

class Solution {
public:
    int FirstNotRepeatingChar(string str) {
        int len = str.size();

        map mp;
        for (int i = 0; i < len; ++i){
            mp[str[i]] ++;
        }

        for (int i = 0; i < len; ++i){
            if(mp[str[i]] == 1){
                return i;
            }
        }

        return -1;
    }
};

int main(){
    Solution ss;
    string str = "abaccdeff";
    cout<
  • 思路二,用数组实现一个简易版哈希表
#include
using namespace std;

class Solution {
public:
    int FirstNotRepeatingChar(string str) {
        int len = str.size();

        int *mp = new int[256]; // 字符共计256种
        for (int i = 0; i < len; ++i){
            mp[str[i]] ++;
        }

        for (int i = 0; i < len; ++i){
            if(mp[str[i]] == 1){
                return i;
            }
        }
        return -1;
    }
};

int main(){
    Solution ss;
    string str = "abaccdeff";
    cout<

总结展望

  • 哈希表的应用

你可能感兴趣的:(<剑指Offer>面试题50(1): 字符串中第一个只出现一次的字符)