求一個字符串中對稱子字符串的最大長度即最長回文字串


題目:

輸入一個字符串,輸出該字符串中對稱的子字符串的最大長度。比如輸入字符串“google”,由於該字符串里最長的對稱子字符串是“goog”,因此輸出 4。

解題思路:

方法一:判斷字符串的每一個子串,若是對稱的,則求出它的長度即可。這種辦法對每一個子串,從兩頭向中間判斷是不是子串。總的時間復雜度為O(n^3),

下面給出時間復雜度是O(n^2)的思路。

方法二:與方法一正好相反,字符串中的每一個開始,向兩邊擴展,此時可分為兩種情況:

(1)對稱子串長度是奇數時, 以當前字符為對稱軸向兩邊擴展比較

(2)對稱子串長度是偶數時,以當前字符和它右邊的字符為對稱軸向兩邊擴展

實現代碼:

#include <iostream>
#include <cstring>
int get_maxlen(const char *str){
    
    const char * current=str;
    int max_len=1;
    int temp_len=1;
    
    while(*current){
        //奇數長度對稱字符串處理
        const char * begin=current-1;
        const char * end=current+1;
        while(begin>=str && *end && *begin==*end){
            begin--;
            end++;
        }
        temp_len=end-begin-1;
        if(temp_len>max_len)
            max_len=temp_len;
        //偶數長度對稱字符串處理
        begin=current;
        end=current+1;
        while(begin>=str && *end && *begin==*end){
            begin--;
            end++;
        }
        temp_len=end-begin-1;
        if(temp_len>max_len)
            max_len=temp_len;
        current++;
    }
    return max_len;
}
int main()
{
    const char * str="googleaelg";
    int ret = get_maxlen(str);
    std::cout<<ret<<std::endl;
    return 0;
}

實際上,求字符串最長對稱字串即為找最長回文字串,在這篇博文中提到了兩種解題思路,第一種復雜度為O(n),詳情請查看:http://www.cnblogs.com/mickole/articles/3578298.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM