剑指offer-字符串中第一个只出现一次的字符

/*******************************************************************
Copyright(c) 2016, Tyrone Li
All rights reserved.
*******************************************************************/
// 作者:TyroneLi
//

/*
Q:
    第一个只出现一次的字符:
        在字符串中找出第一个只出现一次的字符,如”abaccdeff",则输出"b".
S:
    1. 这里使用空间换时间的做法,用一个容器来保存扫描到的字符在字符串中已经出现的次数。
       也就是该容器把一个字符映射成一个数字,而在数据结构中哈希表正是这样。字符表示的ASCII表
       一共包含有2**8个字符,因此我们使用一个256大小的辅助char数组来保存每个字符的出现次数。
*/

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cstdlib>


char firstNotRepeatchar(char*pString)
{
    if(pString == nullptr)
        return '\0';
    
    unsigned int hashTable[256];
    for(int i = 0; i < 256; ++i)
        hashTable[i] = 0;
    
    char*pHashKey = pString;
    while((*pHashKey) != '\0')
    {
        hashTable[*(pHashKey)]++;
        pHashKey++;
    }

    pHashKey = pString;
    while((*pHashKey) != '\0')
    {
        if(hashTable[*pHashKey] == 1)
            return *pHashKey;
        pHashKey++;
    }
    return *pHashKey;
}

void test_1()
{
    std::cout << "Test 1" << std::endl;
    char*str = "abaccdeff";
    std::cout << "input : " << str << std::endl;
    std::cout << firstNotRepeatchar(str) << std::endl;
}

void test_2()
{
    std::cout << "Test 2" << std::endl;
    char*str = "aabbccdd";
    std::cout << "input : " << str << std::endl;
    std::cout << firstNotRepeatchar(str) << std::endl;
}

void test_3()
{
    std::cout << "Test 3" << std::endl;
    char*str = "abcdefg";
    std::cout << "input : " << str << std::endl;
    std::cout << firstNotRepeatchar(str) << std::endl;
}

void test_4()
{
    std::cout << "Test 4" << std::endl;
    char*str = nullptr;
    std::cout << "input : " << str << std::endl;
    std::cout << firstNotRepeatchar(str) << std::endl;
}

void test_firstNotRepeatchar()
{
    test_1();
    test_2();
    test_3();
    test_4();
}

int main(int argc, char**argv)
{
    test_firstNotRepeatchar();

    return 0;
}
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值