首页 > 其他 > 详细

《剑指offer》第五十题(字符串中第一个只出现一次的字符)

时间:2019-03-13 22:44:47      阅读:166      评论:0      收藏:0      [点我收藏+]
// 面试题50(一):字符串中第一个只出现一次的字符
// 题目:在字符串中找出第一个只出现一次的字符。如输入"abaccdeff",则输出
// ‘b‘。

#include <iostream>
#include <string>
//使用一个长度为常量的哈希表,两次遍历,时间复杂度O(n),空间复杂度O(1)
char FirstNotRepeatingChar(const char* pString)
{
    if (pString == nullptr)
        return \0;

    const int tableSize = 256;
    unsigned int hashTable[tableSize];//建立一个简单的哈希表,键值为ASCII码的int值,值为其个数
    for (unsigned int i = 0; i < tableSize; ++i)
        hashTable[i] = 0;

    const char* pHashKey = pString;
    while (*(pHashKey) != \0)//第一次遍历,统计pString字符串中每个字符的个数
        hashTable[*(pHashKey++)] ++;

    pHashKey = pString;
    while (*pHashKey != \0)//第二次遍历,检查哈希表中第一个值为1的键值
    {
        if (hashTable[*pHashKey] == 1)
            return *pHashKey;

        pHashKey++;
    }

    return \0;
}

// ====================测试代码====================
void Test(const char* pString, char expected)
{
    if (FirstNotRepeatingChar(pString) == expected)
        printf("Test passed.\n");
    else
        printf("Test failed.\n");
}

int main()
{
    // 常规输入测试,存在只出现一次的字符
    Test("google", l);

    // 常规输入测试,不存在只出现一次的字符
    Test("aabccdbd", \0);

    // 常规输入测试,所有字符都只出现一次
    Test("abcdefg", a);

    // 鲁棒性测试,输入nullptr
    Test(nullptr, \0);
    system("pause");
    return 0;
}

技术分享图片

技术分享图片

技术分享图片

技术分享图片

技术分享图片

 

《剑指offer》第五十题(字符串中第一个只出现一次的字符)

原文:https://www.cnblogs.com/CJT-blog/p/10526941.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!