package string; /** * @ProjectName: leetcode * @Package: string * @ClassName: String647 * @Author: markey * @Description:647. åæå串 * ç»å®ä¸ä¸ªå符串ï¼ä½ ç任塿¯è®¡ç®è¿ä¸ªåç¬¦ä¸²ä¸æå¤å°ä¸ªåæå串ã * * å ·æä¸åå¼å§ä½ç½®æç»æä½ç½®çå串ï¼å³ä½¿æ¯ç±ç¸åçåç¬¦ç»æï¼ä¹ä¼è¢«è®¡ä¸ºæ¯ä¸åçå串ã * * ç¤ºä¾ 1: * * è¾å ¥: "abc" * è¾åº: 3 * è§£é: ä¸ä¸ªåæå串: "a", "b", "c". * ç¤ºä¾ 2: * * è¾å ¥: "aaa" * è¾åº: 6 * 说æ: 6个åæå串: "a", "a", "a", "aa", "aa", "aaa". * 注æ: * * è¾å ¥çå符串é¿åº¦ä¸ä¼è¶ è¿1000ã * * æ¥æºï¼åæ£ï¼LeetCodeï¼ * 龿¥ï¼https://leetcode-cn.com/problems/palindromic-substrings * è使å½é¢æ£ç½ç»ææãåä¸è½¬è½½è¯·èç³»å®æ¹ææï¼éåä¸è½¬è½½è¯·æ³¨æåºå¤ã * @Date: 2020/3/23 22:00 * @Version: 1.0 */ public class String647 { // 卿è§åæ³ public int countSubstrings(String s) { int n = s.length(); int[][] dp = new int[n][n]; for (int i = 0; i < n; i++) { dp[i][i] = 1; } // åªéè¦å个ç©éµå³å¯ for (int i = n - 1; i >= 0; i--) { for (int j = i + 1; j < n; j++) { if (j == i + 1) { dp[i][j] = s.charAt(i) == s.charAt(j) ? 1 : 0; continue; } dp[i][j] = (dp[i+1][j-1] == 1 && s.charAt(i) == s.charAt(j)) ? 1 : 0; } } int count = 0; for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { count += dp[i][j]; } } return count; } // åæ²»æ³ public int countSubstrings1(String s) { int count = 0; for (int i = 0; i < s.length(); i++) { count += countSubStrings(s, i, i); count += countSubStrings(s, i, i+1); } return count; } private int countSubStrings(String s, int start, int end) { int count = 0; while (start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end)) { count++; start--; end++; } return count; } }