647. Palindromic Substrings
1. 题目描述
题目链接
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:
The input string length won’t exceed 1000.
2. 题目分析
找出字符串中所以回文串,并且统计数量。回文串就是,从左边遍历和从右边遍历等到的字符串是一样的就叫回文串,如aba,abba等。从我的举例中可以看出,回文串会有两种格式,一种是aba这种,关于中间一个字符对称,另一个种是abba,关于中间一条线对称。
3. 解决思路
既然回文串根据中间“对称”的,那么我们可以从一段字符串的中间,向左右两边遍历比较,如果相等,则说明这是一个回文串,数量加1。但这里面要注意一个细节,就是abba型的字符串,先用中间字符跟右边第一个字符比较,如果相等,再往左右两边比较;如果不相等,则使用aba型的字符串比较方式,直接中间的左边第一个和右边第一个进行比较。
4. 代码实现(java)
package com.algorithm.leetcode.dynamicAllocation;
/**
* Created by 凌 on 2018/12/14.
* 描述:
*/
public class CountSubstrings {
public static void main(String[] args) {
String s = "abbcd";
// String s = "abacd";
// String s = "aaa";
int result = countSubstrings(s);
System.out.println(result);
}
public static int countSubstrings(String s) {
if (s == null || s.isEmpty()){
return 0;
}
int count = s.length();
int mid = 0;
int left = mid;
int right = mid + 1;
int len = s.length();
while (mid < len - 1) {
//如abbcd
if (s.charAt(left) == s.charAt(right)){
while (left >= 0 && right < len && s.charAt(left) == s.charAt(right)) {
count++;
left--;
right++;
}
}
//abacd、aaa
left = mid - 1;
right = mid + 1;
if (left >= 0 && right < len && s.charAt(left) == s.charAt(right)) {
while (left >= 0 && right < len && s.charAt(left) == s.charAt(right)) {
count++;
left--;
right++;
}
}
mid++;
left = mid;
right = mid + 1;
}
return count;
}
}