diff options
| author | Steve Lee <me@xiangyangli.com> | 2018-01-13 05:13:14 +0800 |
|---|---|---|
| committer | Steve Lee <me@xiangyangli.com> | 2018-01-13 05:13:14 +0800 |
| commit | a46ec300092c1ee8ccac629b7f335643f87662f5 (patch) | |
| tree | b03e20d905e6f583df626386164daf4aa5f81519 /Computer_Science/leetcode/5-longest_palindromic_substring.c | |
| parent | 79a9c52fa923fc78074d88463449a8b7f95ca3ef (diff) | |
| download | 42-a46ec300092c1ee8ccac629b7f335643f87662f5.tar.xz 42-a46ec300092c1ee8ccac629b7f335643f87662f5.zip | |
update
Diffstat (limited to 'Computer_Science/leetcode/5-longest_palindromic_substring.c')
| -rw-r--r-- | Computer_Science/leetcode/5-longest_palindromic_substring.c | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/Computer_Science/leetcode/5-longest_palindromic_substring.c b/Computer_Science/leetcode/5-longest_palindromic_substring.c new file mode 100644 index 0000000..ee65b8e --- /dev/null +++ b/Computer_Science/leetcode/5-longest_palindromic_substring.c @@ -0,0 +1,34 @@ +void extend(char *s, int len, int i, int j, int *lo, int *hi) +{ + while(i >= 0 && i < len && s[i] == s[j]) { + i--; + j++; + } + + if(j - i > *hi - *lo) { + *lo = i; + *hi = j; + } +} + +char* longestPalindrome(char* s) { + int *lo, *hi; + int len = strlen(s); + + lo = malloc(sizeof(int)); + hi = malloc(sizeof(int)); + + *lo = *hi = 0; + if(len < 2) + return s; + + for(int i = 0; i < len - 1; i++) { + extend(s, len, i, i, lo, hi); + extend(s, len, i, i + 1, lo, hi); + } + + *(s + (*hi)) = '\0'; + return s + *lo + 1; +} + + |
