First non-repeating character in a stream
Given an input stream of n characters consisting only of small case alphabets the task is to find the first non repeating character each time a character is inserted to the stream.
Example
Flow in stream : a, a, b, c a goes to stream : 1st non repeating element a (a) a goes to stream : no non repeating element -1 (5, 15) b goes to stream : 1st non repeating element is b (a, a, b) c goes to stream : 1st non repeating element is b (a, a, b, c)
Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains an integer N denoting the size of the stream. Then in the next line are x characters which are inserted to the stream.
Output:
For each test case in a new line print the first non repeating elements separated by spaces present in the stream at every instinct when a character is added to the stream, if no such element is present print -1.
Constraints:
1<=T<=200
1<=N<=500
Example:
Input:
2
4
a a b c
3
a a c
Output:
a -1 b b
a -1 c
如何处理重复是个难点,本题考察的是队列
纯字符串处理方法.
1 #include <algorithm> 2 #include <iostream> 3 #include <string> 4 5 using namespace std; 6 7 int main() {//by guxuanqing@gmai.com 8 int T,N; 9 cin >> T; 10 //getchar(); 11 string str; 12 string result; 13 string tmpch; 14 while(T--) 15 { 16 cin >> N;//debug(N); 17 //getchar(); 18 str.clear(); 19 result.clear(); 20 tmpch.clear(); 21 int hashs[128] = {0}; 22 char ch; 23 int i = 0; 24 for(i = 0; i < N; i++) 25 { 26 cin >> ch;//debug(ch); 27 while (ch == ' ') { 28 cin >> ch; 29 } 30 //getchar(); 31 str.push_back(ch);//debug(str); 32 ++hashs[(int)str[i]]; //debug(hashs[str[i]]); 33 if(hashs[(int)str[i]] == 1) 34 { 35 if(tmpch.empty()) 36 { 37 result.push_back(str[i]); 38 }else 39 { 40 result.push_back(tmpch[0]); 41 } 42 tmpch.push_back(str[i]);//the first time occurs,push it back to tmpch 43 }else 44 { 45 // string::size_type n = tmpch.find(str[i]);debug(tmpch); 46 // if(n != string::npos) 47 // { 48 // tmpch.erase(n,n);debug(tmpch); 49 // } 50 auto n = std::find(tmpch.begin(), tmpch.end(), str[i]); 51 if(n != tmpch.end()) tmpch.erase(n); 52 if(tmpch.empty()) 53 { 54 result.push_back('0'); 55 }else 56 { 57 result.push_back(tmpch[0]); 58 } 59 } 60 //debug(result); 61 } 62 for(i = 0; i < N; i++) 63 { 64 if(result[i] == '0') cout << "-1 "; 65 else cout << result[i] << ' '; 66 } 67 cout << endl; 68 } 69 70 return 0; 71 }
0.093s