1. 程式人生 > >程式設計題 字串A在字串B中出現的次數

程式設計題 字串A在字串B中出現的次數

騰訊筆試題之一,過了70%,超時。

輸入:整數k, 字串a,字串b

輸出:字串a中k個字元在b出現的次數。

int main(){
    int k;
    string a;
    string b;
    set<string> tempset;
    while(cin >>k >> a >> b){
        int i =0;
        cout<<a.size();
        unsigned int cnt = 0;
        while(a[i+k-1]!='\0'){
            string temp = a.substr(i,k);
            if(tempset.find(temp) == tempset.end()){
                cout<< temp << ":";
                tempset.insert(temp);
                string::size_type pos = 0;
                while ((pos = b.find(temp, pos)) != string::npos) {
                    cout<< pos << ",";
                    ++cnt;
                    ++pos;
                }
               cout<< cnt << endl;
           }
           i++;
        }
        cout<< "total:"<< cnt<<endl;
    }
    return 0;
    
}