算法题:在一个字符串中找到只出现一次的字符。如输入abaccdeeff,则输出bd。
今天的算法學習還是和字符串有關,這個題目據說是以前的某公司面試的筆試題目。題目意思就是說,在一個字符串中找到只出現了一次的那些字符,并且輸出來。
作為非IT的我,平時使用Matlab比較多。不是科班出身,對于這個題目的理解可能也比較簡單。但是也算是一個算法的鍛煉吧,每天進步一點。一個更主要目的就是養成記錄的習慣,積少成多。
不多說直接上我寫的matlab代碼吧
常規算法 Matlab:常規遍歷
clc clear close all strInput='abaccdeeff'; strLength=size(strInput,2); if strLength==0disp('this string is null !') end marker=ones(1,strLength); count=0; letterAppearedOnce=[]; for i=1:strLengthflag=1;if marker(i)for j=i+1:strLengthif strInput(j)==strInput(i)flag=0;marker(j)=0;%break;endendelseflag=0;continue;endif flagcount=count+1;letterAppearedOnce=[letterAppearedOnce,strInput(i)];end end if count==0disp('there is not letter appearing once ') elseif count==1disp(['these is only ',num2str(count),' letter appearing once !','this letter is ',letterAppearedOnce]); elsedisp(['these are ',num2str(count),' letters appearing once !','there letters are ',letterAppearedOnce]); end這個寫的比較繁瑣,我的思想就是主要遍歷去比較吧,這里marker數組和flag變量比較重要。marker數初始時里面全是1,如果遍歷比較的時候,出現了相同的,那么那個相同的字符的索引對應的marker數組的值為0,例如,
i=1時,遍歷比較剩余的字符
j=3時,發現相同的字符,這marker(3)=0
這樣的話第一層循環到i=3時,判斷一下marker(3)是否為真,不是則停止此次循環,進行下一次循環。
flag變量確定了是否存在出現一次的字符。flag=1,存在,flag=0,不存在。
輸出結果為:
These are 2 letters appearing once !there letters are: bd可以看出來,結果沒有問題!把marker數組的結果貼出來
1 1 0 1 0 1 1 0 1 0再換一個輸入:
strInput='abaccddeeff';得到的結果為:
There is only 1 letter appearing once !this letter is: b同樣還是貼出marker數組:
1 1 0 1 0 1 0 1 0 1 0再換一個輸入,重復的字符在2個以上:
strInput='abacacddeccefeeff';此時的結果為:
these is only 1 letter appearing once !this letter is:bmarker數組為:
1 1 0 1 0 0 1 0 1 0 0 0 1 0 0 0 0這種算法比較的簡單,而且比較的復雜,下面是一種簡單的方法,思想比較好。
一種好的算法:利用字符ASCII碼實現
因為每個字符都有一個ASCII碼,所以可以定義一個用于記錄字符出現次數的數組,用字符的ASCII碼做為數組的下標,當遍歷字符
串時,就給相應下標對應的字符次數加1。這樣對字符串的一次遍歷就能記錄每個字符出現的次數。再找到次數為的1的索引,即
字符出現一次的字符的 ASCII
clc clear close all strInput='abaccdeeff'; strLength=size(strInput,2); if strLength==0disp('this string is null !') end strAscll=zeros(1,256); for i=1:strLength strAscll(abs(strInput(i)))=strAscll(abs(strInput(i)))+1; end char(find(strAscll==1))輸出結果為
ans =bd這種算法十分的簡單明了!幾乎就是一個遍歷,其他的判斷全部都沒有。最后得到的結果就是這么的完美!
Python 3 實現:字典數據結構的利用
Python3 的字典這種數據結構還是比較好的,原理就不多說了,直接看代碼就能體會到這個得妙處:
def find_once_appear_letter(string):d={}onceAppearLetter=''for i in string:d[i]=d.get(i,0)+1for item in d.items():if item[1]==1:onceAppearLetter+=item[0]return onceAppearLetterif __name__ == "__main__":str='abaccdeeff'print('The string is :\n')print(str)print()print('the letters appearing only once are:\n') print(find_once_appear_letter(str))結果為:
完美,學無止境!
艾勇 上海交通大學
2017/7/27
總結
以上是生活随笔為你收集整理的算法题:在一个字符串中找到只出现一次的字符。如输入abaccdeeff,则输出bd。的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 算法题:输入aaaabbbcccccc输
- 下一篇: 常见的股票技术因子学习以及计算