File tree Expand file tree Collapse file tree 1 file changed +72
-0
lines changed
Expand file tree Collapse file tree 1 file changed +72
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ * @lc app=leetcode id=647 lang=javascript
3+ *
4+ * [647] Palindromic Substrings
5+ */
6+
7+ function isPalindromic ( s ) {
8+ let start = 0 ;
9+ let end = s . length - 1 ;
10+
11+ while ( start < end && s [ start ] === s [ end ] ) {
12+ start ++ ;
13+ end -- ;
14+ }
15+
16+ return start >= end ;
17+ }
18+
19+ /**
20+ *
21+ * @param {对称点1 } i
22+ * @param {对称点2 } j
23+ * @param {原始字符串 } s
24+ * @return {以i,j为对称点的字符串s有多少回文串 } count
25+ */
26+ function extendPalindromic ( i , j , s ) {
27+ const n = s . length ;
28+ let count = 0 ;
29+ let start = i ;
30+ let end = j ;
31+ while ( s [ start ] === s [ end ] && ( start >= 0 ) & ( end < n ) ) {
32+ start -- ;
33+ end ++ ;
34+ count ++ ;
35+ }
36+
37+ return count ;
38+ }
39+ /**
40+ * @param {string } s
41+ * @return {number }
42+ */
43+ var countSubstrings = function ( s ) {
44+ // "aaa"
45+ // "abc"
46+ // // 暴力法,空间复杂度O(1) 时间复杂度O(n^3)
47+ // let count = s.length;
48+
49+ // for(let i = 0; i < s.length - 1; i++) {
50+ // for(let j = i + 1; j < s.length; j++) {
51+ // if (isPalindromic(s.substring(i, j + 1))) {
52+ // count++;
53+ // }
54+ // }
55+ // }
56+
57+ // return count;
58+
59+ // 中心扩展法(运用回文的对称性)
60+ // 时间复杂度O(n^2) 空间复杂度O(1)
61+ const n = s . length ;
62+ let count = 0 ;
63+
64+ for ( let i = 0 ; i < n ; i ++ ) {
65+ // 以 字符s[i]为对称点,一共有多少回文字串
66+ count += extendPalindromic ( i , i , s ) ;
67+ // 以 字符s[i]和s[i+1]为对称点,一共有多少回文字串
68+ count += extendPalindromic ( i , i + 1 , s ) ;
69+ }
70+
71+ return count ;
72+ } ;
You can’t perform that action at this time.
0 commit comments