ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

647. Palindromic Substrings

2020-11-06 23:01:42  阅读:215  来源: 互联网

标签:count right string palindromic Palindromic Substrings length 647 left


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++
        }
    }
}

 

标签:count,right,string,palindromic,Palindromic,Substrings,length,647,left
来源: https://www.cnblogs.com/johnnyzhao/p/13939406.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有