同步发于 JuzerTech 网站,里面有我软、硬件学习的纪录与科技产品开箱,欢迎进去观看。
题目为给定一个字符串,请撰写一个代码,回传此字符串中最长的回文。
题目与范例如下
Given a string s
, return the longest palindromic substring in s
.
Example 1:
Input: s = "babad" Output: "bab" Note: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd" Output: "bb"
Example 3:
Input: s = "a" Output: "a"
Example 4:
Input: s = "ac" Output: "a"
Constraints:
1 <= s.length <= 1000
s
consist of only digits and English letters (lower-case and/or upper-case)
我的解题策略为,遍历字符串的每个字符,以每个字符为起始点从前后比对字符是否相同。为了避免起始字符与旁边的字符相等,先使用一个 while 回圈,把与起始字符相同的字符都算进去,再开始左右比较。最后用动态内存配置创立一个要回传的字符串,并把最长的回文复制过去,回传此字符串。
下方为我的代码
char * longestPalindrome(char * s){
int start_index = -1,max = 0,temp = -1,tempL = 0,tempR = 0;
for(int i = 0;i<strlen(s);i++){
tempL = i;
tempR = i;
while(tempR+1<strlen(s)){
if(s[tempR+1] == s[tempR])
tempR++;
else
break;
}
while(tempL-1>=0 && tempR+1<strlen(s)){
if(s[tempL-1] == s[tempR+1]){
tempL--;
tempR++;
}
else{
break;
}
}
if((tempR-tempL+1)>max){
max = tempR-tempL+1;
start_index = tempL;
}
}
char *r = (char*)malloc((max+1)*sizeof(char));
strncpy(r, &s[start_index], max);
r[max] = '\0';
return r;
}
下方为时间与空间之消耗
Runtime: 12 ms, faster than 83.30% of C online submissions for Longest Palindromic Substring.
Memory Usage: 6.2 MB, less than 59.25% of C online submissions for Longest Palindromic Substring.