題目:
請實現一個函數用來找出字符流中第一個只出現一次的字符。例如,當從字符流中只讀出前兩個字符"go"時,第一個只出現一次的字符是"g"。當從該字符流中讀出前六個字符“google"時,第一個只出現一次的字符是"l"。
思路:
字符流:像流水一樣的字符,一去不復返,意味着只能訪問一次。
方法1:將字符流保存起來
通過哈希表統計字符流中每個字符出現的次數,順便將字符流保存在string中,然后再遍歷string,從哈希表中找到第一個出現一次的字符;
方法2:哈希表特殊處理
同樣通過哈希表來統計字符流中每個字符,不過不是統計次數,而是保存位置,哈希表初始化每個鍵值對應的value均為-1,如果字符出現一次,則value等於該字符的下標,如果字符出現兩次,則value等於-2;這樣遍歷哈希表時,第一個value大於0的字符就是第一個出現一次的字符;
代碼:
參考下面的在線測試代碼
在線測試OJ:
http://www.nowcoder.com/books/coding-interviews/00de97733b8e4f97a3fb5c680ee10720?rp=3
AC代碼:
方法1:
class Solution { private: string str; int count[256]={0}; public: //Insert one char from stringstream void Insert(char ch) { str+=ch; count[ch]++; } //return the first appearence once char in current stringstream char FirstAppearingOnce() { int len=str.size(); for(int i=0;i<len;i++){ if(count[str[i]]==1) return str[i]; } return '#'; } };
方法2:(暫未AC,原因不詳)
class Solution { private: int index; int count[256]; public: Solution():index(0){ for(int i=0;i<256;++i) count[i]=-1; } //Insert one char from stringstream void Insert(char ch) { if(count[ch]==-1) count[ch]=index; else if(count[ch]>=0) count[ch]=-2; ++index; } //return the first appearence once char in current stringstream char FirstAppearingOnce() { int minIndex=numeric_limits<int>::max(); for(int i=0;i<256;i++){ if(count[i]>=0 && count[i]<minIndex) return char(i); } return '#'; } };