zoukankan      html  css  js  c++  java
  • JZ-C-35

    剑指offer第三十五题:第一个只出现一次的字符

     1 //============================================================================
     2 // Name        : JZ-C-35.cpp
     3 // Author      : Laughing_Lz
     4 // Version     :
     5 // Copyright   : All Right Reserved
     6 // Description : 第一个只出现一次的字符
     7 //============================================================================
     8 
     9 #include <iostream>
    10 #include <stdio.h>
    11 #include <string>
    12 using namespace std;
    13 
    14 char FirstNotRepeatingChar(char* pString)
    15 {
    16     if(pString == NULL)
    17         return '';
    18 
    19     const int tableSize = 256;
    20     unsigned int hashTable[tableSize];//此处定义的哈希表中,key为字符,字符的ASCII码值为数组下标,value为字符出现次数,
    21     for(unsigned int i = 0; i<tableSize; ++ i)
    22         hashTable[i] = 0;
    23 
    24     char* pHashKey = pString;
    25     while(*(pHashKey) != '')//第一次遍历字符串
    26         hashTable[*(pHashKey++)] ++;//使哈希表中对应字符(数组下标为字符ASCII码值)的出现次数加1
    27 
    28     pHashKey = pString;//再将指针重新指向pString
    29     while(*pHashKey != '')
    30     {
    31         if(hashTable[*pHashKey] == 1)//遇到第一个value为1的立即跳出循环,返回
    32             return *pHashKey;
    33 
    34         pHashKey++;
    35     }
    36 
    37     return '';
    38 }
    39 
    40 // ====================测试代码====================
    41 void Test(char* pString, char expected)
    42 {
    43     if(FirstNotRepeatingChar(pString) == expected)
    44         printf("Test passed.
    ");
    45     else
    46         printf("Test failed.
    ");
    47 }
    48 
    49 int main(int argc, char** argv)
    50 {
    51     // 常规输入测试,存在只出现一次的字符
    52     Test("google", 'l');
    53 
    54     // 常规输入测试,不存在只出现一次的字符
    55     Test("aabccdbd", '');
    56 
    57     // 常规输入测试,所有字符都只出现一次
    58     Test("abcdefg", 'a');
    59 
    60     // 鲁棒性测试,输入NULL
    61     Test(NULL, '');
    62 
    63     return 0;
    64 }
  • 相关阅读:
    今天发现之前瑞乐做的登录和注册居然都是用的get请求,瞬间出了一身冷汗.
    用grunt进行前端工程化之路
    移动端开发库zepto 之我思
    构造高度自适应的textarea
    maxlength属性在textarea里奇怪的表现
    在windows下使用linux的开发环境
    移动web开发的一些坑
    [译]开始学习webpack
    完美解决移动Web小于12px文字居中的问题
    再谈移动端Web屏幕适配
  • 原文地址:https://www.cnblogs.com/Laughing-Lz/p/5604583.html
Copyright © 2011-2022 走看看