字串中最大對稱子串的長度(C++軟體工程師面試題)__C++

來源:互聯網
上載者:User

轉載:請註明出處,http://blog.csdn.net/zonghongyan314/article/details/41787877,謝謝。

最近看了一個關於求字串中最大對稱子串的長度的比較有意思的演算法,與大家分享一下。

思路:借用next數組防止回朔比較,例如:字串str:"abcxxxxxcbvvvvv",它對應的next數組值:

  0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
str: a b c x x x x x c b v v v v v
next: 1 1 1 1 2 3 4 5 7 9 1 2 3 4 5
將“死磕類”的演算法時間複雜度提高到O(n)。與KMP的next異曲同工O(∩_∩)O~, 只可惜至今沒有理解KMP。


#include<iostream>using namespace std;/***********************************************************@Author仁子欣****2014年12月7號****************功能:輸入一個字串,輸出該字串中最大對稱子串的長度例如:"abacc"返回3,"a"返回1,abb返回4;輸入:字串str返回:int最大對稱子串的長度*****************************************************/int StrSymmetricCounts(const char* str);int main(){    char* str="abcxxxxxxxxccccc";printf("源字串為:%s\n",str);int len = StrSymmetricCounts(str);printf("最大對稱子串長度:%d\n",len);return 0;}int StrSymmetricCounts(const char* str){if(str==NULL)return-1;int len=strlen(str);int maxlen=1;int next[30];//next數組類似KMP中的next數組             next[0]=1;int i=1;while(i<len){int max=1;if((i-next[i-1]-1)>=0 && str[i]==str[i-next[i-1]-1]){//通過next數組回退比較max = max > (next[i-1]+2) ? max: (next[i-1]+2);}int k=1;while(str[i]==str[i-k])//如果字串的數組相鄰的相等k++;max = max > k?max: k;next[i]=max;//將next數組進行賦值cout<<"next["<<i<<"]="<<next[i]<<"; "<<endl;if(next[i]>maxlen){maxlen=next[i];   }                i++;}return maxlen;} 


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.