647. Palindromic Substrings

复制代码
package LeetCode_647

/**
 * 647. Palindromic Substrings
 * https://leetcode.com/problems/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".

Note:
1. The input string length won't exceed 1000.
 * */
class Solution {
    /*
    * solution: check the palindrome of odd length palindromic substring and even length palindromic substring,
    * for example: aabaa, checking:
     loop 1. center on a and aa, scan to left and right,
     2. center on a and ab, scan to left and right,
     3. center on b and ba, scan to left and right,

    * Time complexity:O(n^2), Space complexity:O(1)
    * */

    private var count = 0

    fun countSubstrings(s: String): Int {
        if (s == null || s.isEmpty()) {
            return 0
        }
        for (i in s.indices) {
            //check odd length
            checkPalindrome(s, i, i)
            //check even length
            checkPalindrome(s, i, i + 1)
        }
        return count
    }

    private fun checkPalindrome(string: String, i_: Int, j_: Int) {
        var i = i_
        var j = j_
        while (i >= 0 && j < string.length && string[i] == string[j]) {
            //if substring is palindrome
            count++
            //to trace string in left direction
            i--
            //to trace string in right direction
            j++
        }
    }
}
复制代码

 

posted @   johnny_zhao  阅读(63)  评论(0编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
点击右上角即可分享
微信分享提示