We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Thesolutionis:foreachcharactercombinationof2,considerifit'spossibleforthemtobetheonlyremainingcharacters.ex:aacbbThereare3scenariostoconsider:1.only'a'and'b'remaining.It's"aabb",anddoesn'tsatisfythecriteria.2.only'a'and'c'remaining.It's"aac",alsonotokay.3.only'b'and'c'remaining.It's"cbb",alsonotokay.So,inthefollowing3x3matrix:abcabc(a,b)or(b,a)representsthescenario"only 'a' and 'b' remaining".Whenwereadthefirst'a'in"aacbb",thematrixbecomes:abcaaaabacasofor(a,b),or"if you want only 'a' and 'b' in the remaining string",the'a'willbethelastcharacter.Thenweaddthesecond'a'in"aacbb".Noticethatfor(a,b),'a'isalreadythelastcharacterandaddingitwillcreatean"aa"duplicate.Thus(a,b)isimpossible.
Hope this explanation makes it clear. If not, writing down on a paper helps.
My code:
intalternate(strings){array<array<char,26>,26>tbl_dup;array<array<int,26>,26>tbl_cnt;// Initilizationfor(inti(0);i<26;++i){for(intj(0);j<26;++j){tbl_dup[i][j]='\0';tbl_cnt[i][j]=0;}}// Go over sfor(inti(0);i<s.size();++i){charch=s[i];for(intj(0);j<26;++j){if(tbl_dup[ch-'a'][j]==ch){// The combination of the char ch and the char 'a'+j is impossible.tbl_cnt[ch-'a'][j]=-1;tbl_cnt[j][ch-'a']=-1;}else{boolno_longer_count=(tbl_cnt[ch-'a'][j]==-1);tbl_dup[ch-'a'][j]=ch;if(!no_longer_count)++tbl_cnt[ch-'a'][j];if((ch-'a')!=j){tbl_dup[j][ch-'a']=ch;if(!no_longer_count)++tbl_cnt[j][ch-'a'];}}}}intmax=-1;for(inti(0);i<26;++i){for(intj(i);j<26;++j){if(tbl_cnt[i][j]>max)max=tbl_cnt[i][j];}}return(max<=1)?0:max;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Two Characters
You are viewing a single comment's thread. Return to all comments →
Genius solution. Thanks for sharing!
Hope this explanation makes it clear. If not, writing down on a paper helps. My code: