zoukankan      html  css  js  c++  java
  • 《剑指offer》第五十题(字符串中第一个只出现一次的字符)

    // 面试题50(一):字符串中第一个只出现一次的字符
    // 题目:在字符串中找出第一个只出现一次的字符。如输入"abaccdeff",则输出
    // 'b'。
    
    #include <iostream>
    #include <string>
    //使用一个长度为常量的哈希表,两次遍历,时间复杂度O(n),空间复杂度O(1)
    char FirstNotRepeatingChar(const char* pString)
    {
        if (pString == nullptr)
            return '';
    
        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) != '')//第一次遍历,统计pString字符串中每个字符的个数
            hashTable[*(pHashKey++)] ++;
    
        pHashKey = pString;
        while (*pHashKey != '')//第二次遍历,检查哈希表中第一个值为1的键值
        {
            if (hashTable[*pHashKey] == 1)
                return *pHashKey;
    
            pHashKey++;
        }
    
        return '';
    }
    
    // ====================测试代码====================
    void Test(const char* pString, char expected)
    {
        if (FirstNotRepeatingChar(pString) == expected)
            printf("Test passed.
    ");
        else
            printf("Test failed.
    ");
    }
    
    int main()
    {
        // 常规输入测试,存在只出现一次的字符
        Test("google", 'l');
    
        // 常规输入测试,不存在只出现一次的字符
        Test("aabccdbd", '');
    
        // 常规输入测试,所有字符都只出现一次
        Test("abcdefg", 'a');
    
        // 鲁棒性测试,输入nullptr
        Test(nullptr, '');
        system("pause");
        return 0;
    }

  • 相关阅读:
    反射(8)程序集反射 Type 类
    反射(5)CLR 运行时探测程序集引用的步骤
    反射(1)程序集基础知识
    csc.exe(C# 编译器)
    证书(1)数字签名基础知识
    反射(7)动态程序集加载Load方法
    SignTool.exe(签名工具)
    反射(3)程序集加载 Assembly类
    关于卡巴斯基安全免疫区随笔
    文本提取工具 TextHelper
  • 原文地址:https://www.cnblogs.com/CJT-blog/p/10526941.html
Copyright © 2011-2022 走看看