lundi 30 mai 2016

I am learning programming, I came across Look and Say sequence.I tried to code it in c++

Can you please suggest how I could possibly reduce the complexity of this code.Here is the code I wrote in c++.There might be an algorithm for this problem, but I want to improve my coding skills.Thanks.
Eg:1, 11, 21, 1211, 111221, ...

1 is read off as "one 1" or 11.

11 is read off as "two 1s" or 21.

21 is read off as "one 2, then one 1" or 1211

string countAndSay(int n){
    if(n==1)
    return "1";
    int j;
    string s="1";
    string temp="";
    unordered_map<char,int> dict;
    for(int i=1;i<n;i++){
        for(j=0;j<s.length();++j){

            if(dict.find(s[j])==dict.end() && j==0)
                dict[s[j]]=1;    

            else if(dict.find(s[j])==dict.end()){
                temp+=to_string(dict[s[j-1]]);
                temp+=s[j-1];
                dict.clear();
                dict[s[j]]=1;
            }    
            else
                dict[s[j]]+=1;
        }

            temp+=to_string(dict[s[j-1]]);
            temp+=s[j-1];
            dict.clear();
            s=temp;
            temp="";
    }

    return s;
} 

Aucun commentaire:

Enregistrer un commentaire