求第一個只出現一次的字符(來源於劍指名企offer)

char FirstRepeatChar(char *inputStr)
{
      if(inputStr==NULL)
          return '\0';

      int tableSize=256;
      int * hashTable=new int[tableSize];
      for(int i=0; i<tableSzie;i++)
         hasTable[i]=0;

      char *pStr=inputStr;
      while(*pStr!='\0')
         hashTable[ *(pStr++) ] ++;
      
      pStr=inputStr;
      char result;
      while(*pStr!='\0')
      {
         if( hashTable[*(pStr++) ]==1 )
         {
             delete hashTable;
             return *(pStr--);
          } 
      }
      delete hashTable;
      return '\0';
}



利用哈希表查找效率爲O(1)的優勢特點, 把 輸入的字符串的每個字符存放在哈系表中;然後便利字符串,查找哈系值爲1的索引。該索引就是第一個只出現一次的字符的ASCII值。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章