1. 程式人生 > >【劍指offer】面試題50:(字元流中)第一個只出現一次的字元【C++版本】

【劍指offer】面試題50:(字元流中)第一個只出現一次的字元【C++版本】

題目:字串中第一個只出現一次的字元。

在字串中找出第一個只出現一次的字元。如輸入"abaccdeff",則輸出b

解題思路:

1.使用雜湊表來記錄每個字元出現的次數,因為字元char為8位,總共有256個值,所有雜湊表有256個元素,其中把字元的ASCII碼作為雜湊表的鍵值,而對應鍵值儲存的是該字元出現的次數。
2.那麼對給定的字串進行兩次遍歷,第一遍收集資訊,即統計每個字串出現了多少次。第二次查詢第一個出現一次的字元,即碰到第一個只出現了一次的字元就進行輸出。

雜湊表是一種常用的資料結構,這裡我們使用雜湊表把一個字元對映成一個數字。在STL中,map和unordered_map就實現了雜湊表的功能,同樣使用陣列/vector來實現簡單的雜湊表。

可以AC的程式碼【C++版本】

注意:牛客網上的介面要求返回的是第一次只出現一次的字元的位置,所以和劍指offer上略有不同

#include <vector>                            
#include <iostream>
#include <stdlib.h>
#include <string>
#include <string.h>

using namespace std;

int FirstNotRepeatingChar(string str)
{
    int strSize = str.size();
    //處理錯誤輸入
if(strSize <= 0)return -1; //處理特殊輸入 if(strSize == 1)return 0; //使用vector做一個雜湊表,記錄每個字元出現的次數,全部初始化為0 vector<int> hashTable(256,0); //範圍for迴圈對輸入字串進行第一次遍歷,統計每一種字元出現的次數 for(auto s:str){ hashTable[s]++; } //對輸入字串進行第二次遍歷 for(int i = 0;i != strSize;i++){ if
(hashTable[str[i]] == 1) return i; } return -1; } int main() { cout << "Please enter a string:" << endl; string test; while(cin >> test){ cout << FirstNotRepeatingChar(test) << endl; } return 0; }

相關題目:字元流中第一個只出現一次的字元

1.因為是字元流,所以字元只能一個接著一個從字元流中讀出來。
2.仍然使用雜湊表來解決,這次雜湊表中不記錄字元出現的次數,而是記錄只出現一次的字元首次出現的位置,雜湊表中的元素全部初始化為-1,記錄只出現一次的元素出現的位置,如果出現一次以上則置為-2。因此,每次遍歷雜湊表就能找到第一個只出現一次的字元

#include <limits.h>               
#include <vector>
#include <iostream>
#include <string>
#include <string.h>
#include <algorithm>
#include <stdlib.h>

using namespace std;

//因為是字元流,所以只能一個一個從字元流中讀出來
//仍然使用雜湊表來解決
class charStatistics
{
    public:
        //建構函式
        charStatistics():index(0){
            for(int i = 0;i != 256;i++){
                hashTable[i] = -1;
            }
        }

        //從字元流中提取一個字元,並更新雜湊表
        void Insert(char ch)
        {
            if(hashTable[ch] == -1){
                hashTable[ch] = index;
            }
            else if(hashTable[ch] >= 0){
                hashTable[ch] = -2;
            }

            index++;
        }

        //遍歷雜湊表,返回第一個只出現一次的字元
        char FirstAppearingOnce(){
            int fstPosi = INT_MAX;
            char resu = '#';
            for(int i = 0;i != 256;i++){
                if(hashTable[i] >= 0){
                    if(hashTable[i] < fstPosi){
                        fstPosi = hashTable[i];
                        resu = (char)i;
                    }
                }
            }

            return resu;
        }

    private:
        //雜湊表
        vector<int> hashTable;
        //當前從資料流中提取的字元的個數
        int index;
};