647. Palindromic Substrings
题目描述: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".
题目含义:给定一个字符串,找出子字符串中包含多少个回文子串
思路:遍历string字符串,如果回文子串的长度为奇数,选取当前字符串位置为中间位置,进行回文串判断,如果回文子串的长度为偶数,则选取当前位置与下一个位置为中间位置,进行回文串判断。
代码
package String; /** * @Author OovEver * @Date 2017/12/8 21:03 */ public class LeetCode647 { int count = 0; public int countSubstrings(String s) { for(int i=0;i<s.length();i++) { // i作为middle索引的回文数 extendPalindrome(s, i, i); extendPalindrome(s, i, i + 1); } return count; } private void extendPalindrome(String s, int left, int right) { while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { left--; right++; count++; } } }