647. Palindromic Substrings

来源:互联网 发布:开票软件 frm 000012 编辑:程序博客网 时间:2024/05/16 14:31

题意是给出一个字符串,从里面找出回文子串的数目。

思路是定义一个计数器count=0,用一个循环,从第i位开始向左右两边一位匹配,匹配到一次就count++,然后分别再向左右两边扩大一位匹配,直到匹配不到或者到达左右两个中的一个。因为回文的奇数和偶数的匹配有区别,所以每一位要从第i位匹配一次,从i到i+1匹配一次。

代码:

public class Solution {int count = 0;public int countSubstrings(String s) {int n = s.length();if (n == 0) return 0;for (int i = 0; i < n; i++) {match(s, i, i + 1);match(s, i, i);}return count;}public void match(String s, int left, int right) {while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {count++;left--;right++;}}}


原创粉丝点击