LeetCode 5. Longest Palindromic Substring ( C ) - Medium

同步发于 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值