File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed
Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change @@ -406,6 +406,63 @@ const countSubstrings = (s) => {
406406}
407407```
408408
409+ TypeScript:
410+
411+ > 动态规划:
412+
413+ ``` typescript
414+ function countSubstrings(s : string ): number {
415+ /**
416+ dp[i][j]: [i,j]区间内的字符串是否为回文(左闭右闭)
417+ */
418+ const length: number = s .length ;
419+ const dp: boolean [][] = new Array (length ).fill (0 )
420+ .map (_ => new Array (length ).fill (false ));
421+ let resCount: number = 0 ;
422+ // 自下而上,自左向右遍历
423+ for (let i = length - 1 ; i >= 0 ; i -- ) {
424+ for (let j = i ; j < length ; j ++ ) {
425+ if (
426+ s [i ] === s [j ] &&
427+ (j - i <= 1 || dp [i + 1 ][j - 1 ] === true )
428+ ) {
429+ dp [i ][j ] = true ;
430+ resCount ++ ;
431+ }
432+ }
433+ }
434+ return resCount ;
435+ };
436+ ```
437+
438+ > 双指针法:
439+
440+ ``` typescript
441+ function countSubstrings(s : string ): number {
442+ const length: number = s .length ;
443+ let resCount: number = 0 ;
444+ for (let i = 0 ; i < length ; i ++ ) {
445+ resCount += expandRange (s , i , i );
446+ resCount += expandRange (s , i , i + 1 );
447+ }
448+ return resCount ;
449+ };
450+ function expandRange(s : string , left : number , right : number ): number {
451+ let palindromeNum: number = 0 ;
452+ while (
453+ left >= 0 && right < s .length &&
454+ s [left ] === s [right ]
455+ ) {
456+ palindromeNum ++ ;
457+ left -- ;
458+ right ++ ;
459+ }
460+ return palindromeNum ;
461+ }
462+ ```
463+
464+
465+
409466
410467-----------------------
411468<div align =" center " ><img src =https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width =500 > </img ></div >
You can’t perform that action at this time.
0 commit comments