zoukankan      html  css  js  c++  java
  • 第一次只出现一次的字符

    题目:在字符串中找出第一个只出现一次的字符。如输入“abaccdeff”,则输出‘b’。

    思路1:遍历,也就是从头开始取字符串中的一个字符,将其与其后的所有字符比较,如果有相同的字符,那么就证明它不是只出现一次的字符。当第一次出现遍历完其后字符并且没有重复时,表明这个字符就是“第一个只出现一次的字符”。

    思路2:我们可以定义哈希表的键值(Key)是字符的ASCII值,而值(Value)是该字符出现的次数。同时我们需要扫描两次字符串,第一次扫描字符串时,每扫描到一个字符就在哈希表的对应项中把次数加1。接下来第二次扫描的时候,没扫描到一个字符就能在哈希表中得到该字符出现的次数。找出第一个Value为1的那个key就是我们需要找到那个字符。

     1 #include <string>
     2 #include "stdafx.h"
     3 
     4 char FirstNotRepeatingChar(char* pString)
     5 {
     6      if(pString == NULL)
     7          return '';
     8 
     9      const int tableSize = 256;
    10      unsigned int hashTable[tableSize];
    11      for(unsigned int i = 0;i < tableSize ; ++i)
    12          hashTable[i] = 0;
    13 
    14      char* pHashKey = pString;
    15      while(*pHashKey != '')
    16          hashTable[*(pHashKey++)] ++;
    17 
    18      pHashKey = pString;
    19      while(*pHashKey != '')
    20      {
    21          if(hashTable[*pHashKey] == 1)
    22              return *pHashKey;
    23 
    24          pHashKey ++ ;
    25      }
    26 
    27      return '';
    28  }
    29 
    30 
    31 int main()
    32 {
    33     
    34     char* pString = "google";
    35     printf("%c
    ", FirstNotRepeatingChar(pString));
    36     
    37     pString = "abcdefg";
    38     printf("%c
    ", FirstNotRepeatingChar(pString));
    39     
    40     return 0;
    41 }

  • 相关阅读:
    ruby中的特殊字符
    android and webview
    ActiveRecord::Base.establish_connection
    Ruby 创建目录
    不能手动输入或粘贴
    eclipse找不到 help>software update>find and install
    PL/SQL 创建、查看、操作用户
    XML文件
    javascript 获取页面高度(多种浏览器)(转)
    Eclipse to android
  • 原文地址:https://www.cnblogs.com/sankexin/p/5634174.html
Copyright © 2011-2022 走看看