首页 > 其他 > 详细

[LeetCode] 5. Longest Palindromic Substring

时间:2016-08-05 11:44:35      阅读:137      评论:0      收藏:0      [点我收藏+]
#include <stdio.h>

// 5. Longest Palindromic Substring
// Given a string S, find the longest palindromic substring in S. 
// You may assume that the maximum length of S is 1000, 
// and there exists one unique longest palindromic substring.
// https://leetcode.com/problems/longest-palindromic-substring/

// Algorithm:
//   c a b a a
// c 1 0 0 0 0
// a   1 0 1 0
// b     1 0 0
// a       1 1
// a         1
// since 1~3 is longer than 3~4, 
// longest palindromic substring is s[1~3], i.e., aba.

char* longestPalindrome(char* s) {

    int debug = 0;

    // int len = (sizeof(s) - 2) / sizeof(s[0]);
    int len = 0;
    while (s[len] != \0) {
        len++;
    }
    if (debug) printf("s = *%s*, len = %d\n", s, len);

    int T[len][len];
    int start = 0, end = 0;
    for (int i = len - 1; i >= 0; i--) {
        for (int j = len - 1; j >= i; j--) {
            if (i == j) {
                T[i][j] = 1;
            } else if (s[i] == s[j]) {
                if (i + 1 == j) {
                    T[i][j] = 1;
                } else {
                    T[i][j] = T[i + 1][j - 1];
                }
            } else if (s[i] != s[j]) {
                T[i][j] = 0;
            }

            if (T[i][j] == 1 && j - i >= end - start) {
                start = i;
                end = j;
            }

            if (debug) printf("i = %d, j = %d; start = %d, end = %d\n", i, j, start, end);
        }
    }

    // char result[end - start + 1 + 1];
    static char result[1000 + 1];    // 1 for ‘\0‘    
    for (int i = 0; i <= end - start; i++) {
        result[i] = s[i + start];
        if (debug) printf("result[%d] = s[%d + %d] = s[%d] = %c\n", i, i, start, i + start, s[i + start]);
    }
    result[end - start + 1] = \0;    // IMPORTANT
    if (debug) printf("resut = *%s*\n", result);

    // *** warning: address of stack memory
    // associated with local variable ‘result‘ returned
    // result 是局部变量, 退出函数后会被释放, 所以在主函数中打印它会有不可预知后果.
    // SOLUTION: result 改成静态,且分配 1000 + 1 个空间。
    // TODO: 有没有办法不假设1000, 而是用 end - start + 1 + 1 ?
    return result;    
}

int main() {
    char *str = longestPalindrome("cabaa");
    printf("result = *%s*\n", str);
    return 0;
}

 

[LeetCode] 5. Longest Palindromic Substring

原文:http://www.cnblogs.com/skyssky/p/5740384.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!