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
1
+ /**
2
+ * [Problem]: [647] Palindromic Substrings
3
+ * (https://leetcode.com/problems/palindromic-substrings/description/)
4
+ */
5
+
6
+ function countSubstrings ( s : string ) : number {
7
+ //시간복잡도 O(n^3)
8
+ //공간복잡도 O(1)
9
+ function bruteForceFunc ( s : string ) : number {
10
+ let count = 0 ;
11
+
12
+ for ( let i = 0 ; i < s . length ; i ++ ) {
13
+ for ( let j = i ; j < s . length ; j ++ ) {
14
+ if ( isPanlindrome ( i , j ) ) count ++ ;
15
+ }
16
+ }
17
+
18
+ function isPanlindrome ( left : number , right : number ) : boolean {
19
+ while ( left < right ) {
20
+ if ( s [ left ] !== s [ right ] ) return false ;
21
+ left ++ ;
22
+ right -- ;
23
+ }
24
+
25
+ return true ;
26
+ }
27
+
28
+ return count ;
29
+ }
30
+ //시간복잡도 O(n^2)
31
+ //공간복잡도 O(n^2)
32
+ function dpFunc ( s : string ) : number {
33
+ const dp = new Map < string , boolean > ( ) ;
34
+ let count = 0 ;
35
+
36
+ for ( let end = 0 ; end < s . length ; end ++ ) {
37
+ for ( let start = end ; start >= 0 ; start -- ) {
38
+ const key = `${ start } ,${ end } ` ;
39
+ if ( start === end ) {
40
+ dp . set ( key , true ) ;
41
+ } else if ( start + 1 === end ) {
42
+ dp . set ( key , s [ start ] === s [ end ] ) ;
43
+ } else {
44
+ const innerKey = `${ start + 1 } ,${ end - 1 } ` ;
45
+ const isInnerPalindrome = dp . get ( innerKey ) || false ;
46
+ dp . set ( key , s [ start ] === s [ end ] && isInnerPalindrome ) ;
47
+ }
48
+
49
+ if ( dp . get ( key ) ) {
50
+ count ++ ;
51
+ }
52
+ }
53
+ }
54
+
55
+ return count ;
56
+ }
57
+ }
You can’t perform that action at this time.
0 commit comments