Leetcode 647.回文子串

回文子串

给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。

具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被计为是不同的子串。

示例 1:

输入: "abc"

输出: 3

解释: 三个回文子串: "a", "b", "c".

示例 2:

输入: "aaa"

输出: 6

说明: 6个回文子串: "a", "a", "a", "aa", "aa", "aaa".

注意:

  1. 输入的字符串长度不会超过1000。

 

 1 class Solution {
 2     public int countSubstrings(String S) {
 3         int N = S.length(), ans = 0;
 4         for (int center = 0; center <= 2*N-1; ++center) {
 5             int left = center / 2;
 6             int right = left + center % 2;
 7             while (left >= 0 && right < N && S.charAt(left) == S.charAt(right)) {
 8                 ans++;
 9                 left--;
10                 right++;
11             }
12         }
13         return ans;
14     }
15 }

 

 

猜你喜欢

转载自www.cnblogs.com/kexinxin/p/10383064.html
今日推荐