码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode-647-Palindromic Substrings]

时间:2017-07-24 16:23:08      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:output   different   inpu   solution   imp   exp   mic   一个   nbsp   

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: 3
Explanation: Three palindromic strings: "a", "b", "c".

 

Example 2:

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

 

Note:

  1. The input string length won‘t exceed 1000.

思路:

从字符串s中的位置s[i]出发,分别判断奇数长度和偶数长度的子字符串是否为回文串。

判断奇数长度: 将index指向同一个字符s[i],然后循环判断s[i-1]和s[i+1]是否相等。

判断偶数长度: 将index指向相邻两个字符s[i],s[i+1],然后循环判断s[i]和s[i+1]是否相等,,然后分别向左和向右移动字符指针。

void ifsub(string& s,int l,int r,int& cnt)
    {
        while (l >= 0 && r < s.length() && s[l] == s[r])
        {
            cnt++;
            l--;
            r++;
        }
    }
    int countSubstrings(string s)
    {
        if (s.length() == 0)return 0;
        int cnt = 0;
        for (int i = 0; i < s.length();i++)
        {
            ifsub(s, i, i, cnt);//判断奇数情况
            ifsub(s, i, i+1, cnt);//判断偶数情况
        }
        return cnt;
    }

参考:

https://discuss.leetcode.com/topic/96884/very-simple-java-solution-with-detail-explanation

[leetcode-647-Palindromic Substrings]

标签:output   different   inpu   solution   imp   exp   mic   一个   nbsp   

原文地址:http://www.cnblogs.com/hellowooorld/p/7229209.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!