Topic:
Finds the first occurrence of a character in a string. If you enter Abaccdeff, then output B.
Ideas:
We can iterate through each character in turn, that is, the number of times each character is asked, and the string is traversed once. But this time complexity is O (n*n).
Consider this, each character corresponds to an ASCII value, we can set an array length of 256, each character ASCII value is the index value of the array. Add one if you encounter the same.
The last traversal of the first occurrence of a character.
Code:
#include <iostream> #include <string>using namespace Std;char firstsingle (string ss) {int count[256]={0}; for (int i=0;i<ss.length (); i++) {count[ss[i]]++;} For (I=0;i<ss.length (); i++) {if (count[ss[i]]==1) return ss[i];} Return ' & ';} int main () { string Str;cin>>str;char res;res=firstsingle (str); Cout<<res<<endl;return 0;}
Post
Although this solution is convenient but we consume a lot of space, how can we reduce space? can be considered with bitmap solution. We can think about it.
(Title: Programming Beauty)
String: Finds the first occurrence of a character in a string