給定乙個字串 s,找到 s 中最長的回文子串。你可以假設 s 的最大長度為 1000。
示例 1:
輸入: "babad"
輸出: "bab"
注意: "aba" 也是乙個有效答案。
示例 2:
輸入: "cbbd"
輸出: "bb"
因為是找回文子串,所以使用中心擴充套件法,中心擴充套件有兩種,一種是以單個字元[i,i]為中心,乙個是以雙個字元[i, i+1] 為中心,一旦發現首尾相同,就再向前後擴充套件乙個,增大範圍。知道擴充套件到原有字串範圍以外(left >=0 && right < n)。如果這是發現回文串更長,我們就將這個首尾和長度記錄下來
/*
* 需求
給定乙個字串 s,找到 s 中最長的回文子串。你可以假設 s 的最大長度為 1000。
示例 1:
輸入: "babad"
輸出: "bab"
注意: "aba" 也是乙個有效答案。
示例 2:
輸入: "cbbd"
輸出: "bb"
gcc longestpalindrome.c -g -o a.exe -ddebug
*/#include #include #include #include #include #ifdef debug
#define log(fmt, args...) fprintf(stdout, fmt, ##args)
#define breaker(a, b, c) breaker(a, b, c)
#else
#define log(fmt,...)
#define breaker(a, b, c)
#endif
#define true 1
#define false 0
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) > (b) ? (b) : (a))
char * longestpalindrome2(char * s)
int len = 0;
int len1 = 0, len2 = 0;
int substart = 0, subend = 0;
int size = 0;
int i = 0;
char * sub = null;
size = strlen(s);
for(i = 0; i < size; i++)
} len = subend - substart + 1 + 1; /*減去start 補充1,'\0'再補充1*/
sub = (char *)malloc(len * sizeof(char));
memcpy(sub, s + substart, len - 1); /*最後乙個是'\0', 不用拷貝,單獨賦值*/
sub[len - 1] = '\0'; /*字串結尾*/
return sub;
}void testlongestpalindrome(void)
/*testcase 2*/
s = longestpalindrome(str1);
if(null != s)
/*testcase 3*/
s = longestpalindrome(str2);
if(null != s)
/*testcase 4*/
s = longestpalindrome(str3);
if(null != s)
/*testcase 5*/
s = longestpalindrome(str4);
if(null != s)
/*testcase 1*/
s = longestpalindrome2(str);
if(null != s)
/*testcase 2*/
s = longestpalindrome2(str1);
if(null != s)
/*testcase 3*/
s = longestpalindrome2(str2);
if(null != s)
/*testcase 4*/
s = longestpalindrome2(str3);
if(null != s)
/*testcase 5*/
s = longestpalindrome2(str4);
if(null != s)
#endif
return; }
int main(int argc, char ** ar**)
gcc longestpalindrome.c -g -o a.exe -ddebug
************ testlongestpalindrome ************
the longest palindrome of babad is bab
the longest palindrome of cbbd is bb
the longest palindrome of a is a
the longest palindrome of is
the longest palindrome of ac is c
the longest palindrome2 of babad is bab
the longest palindrome2 of cbbd is bb
the longest palindrome2 of a is a
the longest palindrome2 of is
the longest palindrome2 of ac is a
演算法訓練 最長回文子串(中心擴充套件演算法)
問題描述 給定乙個字串 s,找到 s 中最長的回文子串。你可以假設 s 的最大長度為 1000。示例1 輸入 babad 輸出 bab 注意 aba 也是乙個有效答案。示例2 輸入 cbbd 輸出 bb 這是leetcode的一道關於字串的題,在官方給出的題解有5種思路,分別是 最長公共子串 暴力法...
最長回文子串的找法(c語言)
回文串 時間限制 c c 1秒,其他語言2秒 空間限制 c c 32768k,其他語言65536k 64bit io format lld 題目描述 既然大家都知道回文串是怎麼回事了,那我們就長話短說,現在有乙個字串,長度小於1200,我想知道最長的回文子串長度是多少。輸入描述 多組輸入,輸入字串只...
回文串之中心擴充套件法
中心擴充套件法可以幫助減少在回文子串中暴力遍歷的一次迴圈,在普通暴力遍歷中,我們需要兩次迴圈分別確定左指標和右指標 即回文子串的左右邊界 然後還有一次迴圈向中間靠攏判斷。中心擴充套件法將向中心靠攏的這一步改為了由中心向兩邊延申,由於回文子串有奇數和偶數之分,所以中心擴充套件法的起始點需要分兩種情況討...