Recently, in order to find an internship, you need to practice the algorithm, so you are ready to brush the questions. leetcode is used. But after brushing for a period of time, I found that the idea of the topic I brushed before was not very clear, so I record my thoughts and code here for review and understanding later.
Fifth questions Longest Palindromic Substring
Question 5 Longest Palindromic Substring
Topic:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example:
Input: "cbbd"
Output: "bb"
Train of thought:
When I saw the topic, I first thought about using stack to solve it. Later, I thought that if there were any more, the elements of the stack pushed out in the middle would be useless. Then honestly look for the same elements from the middle to both sides. In this case, we should consider two situations: one is that there is only one element in the middle of the palindrome itself, and the other two elements are equal to each other to represent the palindrome. The idea is basically the same, but in order to reduce the number of judgments, my boundary conditions have been limited. Let's go directly to the code below:
char* longestPalindrome(char* s) {
if(s[0] == '\0')return NULL;
int tmplen = 1;
int maxlen = 1;
int maxindex = 0;
int tmpindex = 0;
int slen = strlen(s);
for(int i = 0; i < (slen-maxlen/2); i++){//Reduce the number of judgements
int j = i-1;
int k = i+1;
while(j>=0 && (k<=slen&&s[j]==s[k])){//The middle element has its own palindrome
j--;k++;tmplen+=2;
}
tmpindex = j+1;
if(s[i] == s[i+1]){//Two Element Palindromes
int j2 = i-1;
int k2 = i+2;
int tmplen2 =2;
while(j2>=0 && (k2<=slen&&s[j2]==s[k2])){
j2--;k2++;tmplen2+=2;
}
if(tmplen2 > tmplen){
tmplen = tmplen2;
tmpindex = j2+1;
}
}
if(tmplen > maxlen){
maxlen = tmplen;
maxindex = tmpindex;
}
tmplen = 1;
//printf("maxlen = %d\n",maxlen);
}
printf("maxlen = %d,maxindex =%d\n",maxlen,maxindex);
char *ret = (char *)malloc(sizeof(char)*1001);
for(int i = 0; i < maxlen; i++){
ret[i] = s[maxindex+i];
}
ret[maxlen]='\0';
return ret;
}
It's hard to find a job, so let's brush it down together!!!
Meaning Group Come on!!!