算法题:输入aaaabbbcccccc输出a4b3c6。
今日在地鐵上瀏覽今日頭條的時候看到這么個小題目,說是輸出一長串字符串,輸出字母串類別并且統(tǒng)計其出現(xiàn)次數(shù),然后按照順序將其輸出來。例如輸入aaaabbbcccccc,輸出a4b3c6。
最近也一直在學習,所以就想著就Matlab來試了試,題目是很簡單的。不是IT出身,所以可能自己的想法比較簡單,但是也算是一個學習吧!
主要是為了養(yǎng)成記錄的習慣,所以就把這個簡單的東西記錄下來。
直接上代碼吧。
clc clear close strInput='aaaabbbcccccc'; str=strInput'; strCount=tabulate(str); letterTypeNumber=size(strCount,1); strAppend=[]; for i=1:letterTypeNumberstrAppend=[strAppend,strCount{i,1},num2str(strCount{i,2})]; end disp('The final string ouyput answer is : ') strOutput=strAppend最后的輸出結果為:
The final string ouyput answer is : strOutput =a4b3c6看了看,最后的目的達到了。不過這里主要是使用了matlab的一個自帶的統(tǒng)計函數(shù)tabulate。執(zhí)行了下面這一句:
strCount=tabulate(str);得到的結果為:
abc43630.769223.076946.1538
這個矩陣的第一列就是字母的類別統(tǒng)計,第二列是字母的出現(xiàn)次數(shù)統(tǒng)計,最后一列就是一個占比百分數(shù)。
然后再輸入了一個不僅僅有字母的字符串,包括一些其他的字符。
strInput='~~~@@$@@$%$$%&$&abcabcdefdef***^*^';運行了一下,得到的結果為:
The final string ouyput answer is : strOutput =~3@4$5%2&2a2b2c2d2e2f2*4^2結果也還行。主要是matlab自帶的函數(shù)tabulate很好用吧。
下一步打算不使用matlab自帶的函數(shù)來試試。
clc clear close %% strInput='aaaabbbcccccc'; strInput=sort(strInput); strLength=size(strInput,2); if strLength~=0temp=1; elsedisp('The Input is null !') endstrCountSum=0; for i=1:strLengthif i==strLengthstrCount(temp)=strLength-strCountSum;strType(temp)=strInput(strLength)break;elseif strInput(1,i)~=strInput(1,i+1)if temp-1==0strCount(temp)=i;elsestrCount(temp)=i-strCountSum;endstrType(temp)=strInput(1,i)strCountSum=strCountSum+strCount(temp);temp=temp+1;end endstrAppend=[]; for i=1:tempstrAppend=[strAppend,strType(1,i),num2str(strCount(1,i))]; end disp('The final string ouyput answer is : ') strOutput=strAppend輸出結果為:
The final string ouyput answer is : strOutput =a4b3c6發(fā)現(xiàn),結果也是對的。
然后再輸入了一個不僅僅有字母的字符串,包括一些其他的字符。
strInput='~~~@@$@@$%$$%&$&abcabcdefdef***^*^';輸出的結果為:
The final string ouyput answer is : strOutput =$5%2&2*4@4^2a2b2c2d2e2f2~3結果也是對的,但是和上面的結果稍微有一點排序上的差別。這個目前還沒弄清楚這個tabulate對于字符的排序和sort函數(shù)對于字符的排序有什么區(qū)別。
Python字典實現(xiàn)該算法題
最近在學習Python數(shù)據(jù)結構之字典,突然發(fā)現(xiàn),這個數(shù)據(jù)結構還是相當好用的,再聯(lián)想到這個算法題,決定試一試。
話不多說,先上代碼吧
def string_count_append(string):d = {}for i in string:# 相當于創(chuàng)建字典,當沒有key‘i’時,返回該key對應value=0d[i] = d.get(i, 0) + 1# 最終得到一個以出現(xiàn)字符為key,字符出現(xiàn)次數(shù)為value的字典finalString = ''# d.items() 返回字典的key和value且是成對出現(xiàn),為元組類型for i in d.items():#字符連接#'%d'%i[1]實現(xiàn)數(shù)字轉換為字符temp = i[0] + '%d' % i[1]finalString += tempreturn finalString if __name__=="__main__":str = 'aaaabbcccccc'print()print('The string before counting and appending is:\n')print(str)print()print('The string after counting and appending is:\n')print(string_count_append(str))print()得到的結果為:
可以看出來,使用Python以及字典這種數(shù)據(jù)結構,很快就得到結果了。代碼簡單明了。
暫時沒有發(fā)現(xiàn)什么bug。
總結
以上是生活随笔為你收集整理的算法题:输入aaaabbbcccccc输出a4b3c6。的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中国建设银行app怎么查账单明细(《中国
- 下一篇: 算法题:在一个字符串中找到只出现一次的字