Google筆試題:雜湊表的一個意想不到的應用–在字串中尋找第一個只出現一次的字元

來源:互聯網
上載者:User

1.問題描述

在一個字串中找到第一個只出現一次的字元。如輸入AbAssvfFCCBbhV,則輸出v。

 

2.解題思路

如果按照傳統比較的辦法,時間複雜度是O(n*n),這顯然不是Google面試官希望的答案,本題實際上是雜湊表的一個應用,我們舉個簡單例子

比如:輸入AbAcc

我們建立雜湊表

                      0                       1                       2                3                     ...                25                26                 27         28      ....          51

  字元                                     b                        c                                                                                A

出現次數                               1                         2                                                                                 2

這樣只要我們構造好雜湊表,我們可以在O(n)內找到b,而構造雜湊表的時間複雜度是O(n)

話又說回來,世界上沒有完美的事,我們雖然節省了時間,卻要用額外的空間來換

 

3.代碼

/*This is a free Program, You can modify or redistribute it under the terms of GNU*Description:利用雜湊表尋找第一個只出現一次的字元*Language: C++*Development Environment: VC6.0*Author: Wangzhicheng*E-mail: 2363702560@qq.com*Date: 2012/11/29*/#include <iostream>#include <cstdlib>#include <string>#include <cctype>using namespace std;class Solution {private:int n;                 //共52個大小寫字母string s;              //輸入的字串,只能含有大小寫/**雜湊表*@ch:存放字母*@cur:字母出現的次數*/typedef struct Hash {   char ch;int cur;};Hash *HashTable;char answer;           //第一次只出現一次的字元    /**雜湊函數*小寫字母存放0-25的位置*大寫字母存放26-51的位置*/ int HashFunction(char ch) {if(islower(ch)) {return ch-'a';}else return ch-'A'+n/2;}/**裝載雜湊表*/void LoadHashTable() {int i;int pos;for(i=0;s[i];i++) {pos=HashFunction(s[i]);if(!HashTable[pos].ch) {   //該位置為空白HashTable[pos].ch=s[i];HashTable[pos].cur=1;}else HashTable[pos].cur++;}}public:/**建構函式*為雜湊表分配空間*初始化字串*/Solution(const string &str) {n=52;HashTable=new Hash[n];if(!HashTable) {cerr<<"記憶體不足,程式退出!";exit(1);}int i;for(i=0;i<n;i++) {HashTable[i].ch='\0';HashTable[i].cur=0;}s=str;answer='\0';}/**尋找第一次只出現一次的字元的函數*利用雜湊表進行尋找*/void JustDoIt() {LoadHashTable();int i;int pos;for(i=0;i<n;i++) {pos=HashFunction(s[i]);if(HashTable[pos].cur==1) {   //此時該字元出現的次數為1answer=s[i];return;}}}char get() const {return answer;}void Answer() {if(!get()) cout<<"本字串中沒有第一次只出現一次的字元"<<endl;else cout<<"第一次只出現一次的字元是:"<<get()<<endl;}~Solution() {delete []HashTable;}};void main() {string str;cout<<"請輸入一個字串:";cin>>str;if(!cin.good()) {cerr<<"輸入異常!"<<endl;exit(1);}int i;for(i=0;str[i];i++) {if(!islower(str[i]) && !isupper(str[i])) {cerr<<"字串只能含有大小寫字元!"<<endl;return;}}Solution solution(str);solution.JustDoIt();solution.Answer();}

 

4 測試

C代碼:

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <ctype.h>/* * to find the first char which only once ocurred in a string  * use the Hash method to solve the problem * */int HashTable[52];   // contains A-F and a-z character/* * hash function  * */int Hash(char c) {    if(isupper(c)) {return c - 'A';    }    else if(islower(c)) {return 26 + c - 'a';    }}/* * scan the str and load the hash table  * */void LoadHashTable(const char *str) {    int i;    int pos;   // the hash address     for(i = 0;i < strlen(str);i++) {pos = Hash(str[i]);HashTable[pos] += 1;    }}/* * to search the target  * */int Locate(const char *str, char &X) {    int i;    int pos;    int val;int find = 0;   // whether find the result    for(i = 0;i < strlen(str);i++) {pos = Hash(str[i]);val = HashTable[pos];if(val == 1) {/* * to find the target character * */switch(pos/26) {case 0:X = 'A' + pos%26;break;case 1:X = 'a' + pos%26;break;}find = 1;}    }return find;}void main() {    char buf[1024];    char c;    int i;    gets(buf);    for(i = 0;i < strlen(buf);i++) {if(!isupper(buf[i]) && !islower(buf[i])) {    perror("string only can contains character!\n");    exit(1);}    }    LoadHashTable(buf);    if(Locate(buf, c)) {putchar(c);}else perror("沒有出現一次的字母!");    printf("\n");}

測試:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.