Python實現針對給定字串尋找最長非重複子串

來源:互聯網
上載者:User
這篇文章主要介紹了Python實現針對給定字串尋找最長非重複子串的方法,涉及Python針對字串的遍曆、排序、計算等相關操作技巧,需要的朋友可以參考下

本文執行個體講述了Python實現針對給定字串尋找最長非重複子串的方法。分享給大家供大家參考,具體如下:

問題:

給定一個字串,尋找其中最長的重複子序列,如果字串是單個字元組成的話如“aaaaaaaaaaaaa”那麼滿足要求的輸出就是a

思路:

這裡的思路有兩種是我能想到的

(1)從頭開始遍曆字串,設定標誌位,在往後走的過程中當發現和之前標誌位重合的時候就回頭檢查一下這個新出現的子串是否跟前面字串或者前面字串的子串相同,相同則記錄該子串並計數加1,直至處理完畢

(2)利用滑窗切片的機制,產生所有的切片接下來統計和處理,主要利用到了兩次排序的功能

本文採用的是第二種方法,下面是具體實現:


#!usr/bin/env python#encoding:utf-8'''''__Author__:沂水寒城功能:給定一個字串,尋找最長重複子串'''from collections import Counterdef slice_window(one_str,w=1):  '''''  滑窗函數  '''  res_list=[]  for i in range(0,len(one_str)-w+1):    res_list.append(one_str[i:i+w])  return res_listdef main_func(one_str):  '''''  主函數  '''  all_sub=[]  for i in range(1,len(one_str)):    all_sub+=slice_window(one_str,i)  res_dict={}  #print Counter(all_sub)  threshold=Counter(all_sub).most_common(1)[0][1]  slice_w=Counter(all_sub).most_common(1)[0][0]  for one in all_sub:    if one in res_dict:      res_dict[one]+=1    else:      res_dict[one]=1  sorted_list=sorted(res_dict.items(), key=lambda e:e[1], reverse=True)  tmp_list=[one for one in sorted_list if one[1]>=threshold]  tmp_list.sort(lambda x,y:cmp(len(x[0]),len(y[0])),reverse=True)  #print tmp_list  print tmp_list[0][0]if __name__ == '__main__':  print "指令碼之家測試結果:"  one_str='abcabcd'  two_str='abcabcabd'  three_str='bbbbbbb'  main_func(one_str)  main_func(two_str)  main_func(three_str)


結果如下:


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.