LeetCode 647. Palindromic Substrings--回文子串个数

来源:互联网 发布:甲骨文软件 薪资 编辑:程序博客网 时间:2024/06/06 04:13

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

Example 2:

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

Note:

  1. The input string length won't exceed 1000.
package com.main;public class Main {    private int lo, count;    public int countSubstrings(String s) {        if (s == null ) {            return 0;        }        if(s.length() < 2){            return  1;        }        for (int i = 0; i < s.length(); i++) {            extendLongestPalindrome(s, i, i);//输出的子串长度都是奇数,从中间某个位向两边比较            extendLongestPalindrome(s, i, i + 1);//输出的子串长度都是偶数,从中间两个相邻的位分别向两边比较        }        return count;    }    public void extendLongestPalindrome(String s, int j, int k) {        while (j >= 0 && k < s.length() && s.charAt(j) == s.charAt(k)) {            j--;            k++;            count++;        }    }//extendLongestPalindrome    public static void main(String[] args) {        // write your code here        Main main = new Main();        int count = main.countSubstrings("abcDD");//输出6        System.out.println(count);    }}

130 / 130 test cases passed.
Status: Accepted
Runtime: 15 ms
Your runtime beats 66.73 % of java submissions.




原创粉丝点击