From b934f47c83340b91b8a6291d96420978da0ec0e6 Mon Sep 17 00:00:00 2001 From: milu-tao <91822069+milu-tao@users.noreply.github.com> Date: Fri, 24 Mar 2023 22:14:39 +0800 Subject: [PATCH] =?UTF-8?q?Update=200647.=E5=9B=9E=E6=96=87=E5=AD=90?= =?UTF-8?q?=E4=B8=B2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. result 在遍历过程中 ++ 就行,没必要另外计算 2.题目已经表明:s字符串的长度规则是:1 <= s.length <= 1000,所以前面不需要进行判断字符串长度 --- problems/0647.回文子串.md | 33 ++++++++++++--------------------- 1 file changed, 12 insertions(+), 21 deletions(-) diff --git a/problems/0647.回文子串.md b/problems/0647.回文子串.md index 90e6da9f..339247f5 100644 --- a/problems/0647.回文子串.md +++ b/problems/0647.回文子串.md @@ -238,33 +238,24 @@ Java: ```java class Solution { public int countSubstrings(String s) { - int len, ans = 0; - if (s == null || (len = s.length()) < 1) return 0; - //dp[i][j]:s字符串下标i到下标j的字串是否是一个回文串,即s[i, j] + char[] chars = s.toCharArray(); + int len = chars.length; boolean[][] dp = new boolean[len][len]; - for (int j = 0; j < len; j++) { - for (int i = 0; i <= j; i++) { - //当两端字母一样时,才可以两端收缩进一步判断 - if (s.charAt(i) == s.charAt(j)) { - //i++,j--,即两端收缩之后i,j指针指向同一个字符或者i超过j了,必然是一个回文串 - if (j - i < 3) { + int result = 0; + for (int i = len - 1; i >= 0; i--) { + for (int j = i; j < len; j++) { + if (chars[i] == chars[j]) { + if (j - i <= 1) { // 情况一 和 情况二 + result++; + dp[i][j] = true; + } else if (dp[i + 1][j - 1]) { //情况三 + result++; dp[i][j] = true; - } else { - //否则通过收缩之后的字串判断 - dp[i][j] = dp[i + 1][j - 1]; } - } else {//两端字符不一样,不是回文串 - dp[i][j] = false; } } } - //遍历每一个字串,统计回文串个数 - for (int i = 0; i < len; i++) { - for (int j = 0; j < len; j++) { - if (dp[i][j]) ans++; - } - } - return ans; + return result; } } ```