leetcode 647. Palindromic Substrings

来源:互联网 发布:免费tk域名申请 编辑:程序博客网 时间:2024/05/17 07:13

原题:

Given a string, your task is to count how many palindromic substrings in this string.

The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.

Example 1:

Input: "abc"Output: 3Explanation: Three palindromic strings: "a", "b", "c".

Example 2:

Input: "aaa"Output: 6Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

Note:

  1. The input string length won't exceed 1000.
代码如下:

int countSubstrings(char* s) {    int len=strlen(s);    char *test;    test=(char*)malloc(sizeof(char)*(2*len+1));    for(int n=0;n<len;n++)    {        *(test+2*n)='#';        *(test+2*n+1)=*(s+n);    }    *(test+2*len)='#';    //printf("%s",test);    int sum=0;    for(int n=1;n<2*len;n++)    {        //printf("%d",n);        for(int k=0;(n-k)>=0&&(n+k)<2*len+1;k++)        {            if(*(test+n-k)=='#')                continue;            if(*(test+n-k)==*(test+n+k))                sum++;            else                break;            //printf("%c,%c",*(test+n-k),*(test+n+k));        }    }    return sum;}
构造一个半径。其实我也是看别人的方法自己重写的。。。