LeetCode 647. Palindromic Substrings(647. 迴文子串)

647. Palindromic Substringsthis

Given a string, your task is to count how many palindromic substrings in this string.spa

The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.指針

  • Example 1:

Input: "abc"code

Output: 3blog

Explanation: Three palindromic strings: "a", "b", "c".leetcode

  • Example 2:

Input: "aaa"字符串

Output: 6get

Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".input

Note:The input string length won't exceed 1000.string

解題思路:

使用中心擴展方法,每一個字符都是一箇中心,或者兩個相鄰同樣的字符是一箇中心,而後向左右分別遞進判斷可否造成迴文

舉個🌰

  好比字符串是    a   b   a

  遍歷字符串   <-⬆->             迴文子串 a  左邊沒有數據因此只有這一個

                      <-⬆->         迴文子串 b  一個指針向左走一個指針向右走 判斷是否還有對應的子串(aba), 左邊 a 右邊 a 能造成字串,再走沒有數據

                        <-⬆->     迴文字串 a 右邊沒有數據因此結束

  根據上面的流程 最終的字串爲  a,b, aba, a 共4個

 

  固然還有兩個字符同樣的狀況

  好比字符串是   a   b   b   a

  這樣就須要      <-⬆  ⬆->      從中間兩個向外判斷是否能造成迴文子串  

參考代碼:

class Solution {
    // 迴文字串數量
    int count = 0;
    public int countSubstrings(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        for (int i = 0; i < s.length(); i++) {
            // aba -> i 爲 b位置
            helper(s,i,i);
            // abba -> i 爲第一個b位置
            helper(s,i,i+1);
        }
        return count;
    }

    private void helper(String s, int left, int right) {
        while (left >= 0 && right <= s.length() - 1 && s.charAt(left) == s.charAt(right)) {
            count++;
            left--;
            right++;
        }
    }
}
相關文章
相關標籤/搜索