/*******************************************************************
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;
}
剑指offer-字符串中第一个只出现一次的字符
最新推荐文章于 2020-06-06 21:52:01 发布