File tree Expand file tree Collapse file tree 1 file changed +49
-1
lines changed Expand file tree Collapse file tree 1 file changed +49
-1
lines changed Original file line number Diff line number Diff line change 22 * @param {string } s
33 * @return {number }
44 *
5- * νμ΄ λ°©λ²
5+ * νμ΄ λ°©λ² 1
66 *
77 * 1. brute force λ₯Ό μ¬μ©ν΄μ λͺ¨λ κ²½μ°μ μλ₯Ό ꡬνλ€.
88 * 2. ν¬ν¬μΈν°λ₯Ό ν΅ν΄ isPalindrome μ νμΈνλ€.
@@ -46,3 +46,51 @@ var countSubstrings = function(s) {
4646
4747 return count ;
4848} ;
49+
50+ /**
51+ * νμ΄ λ°©λ² 2
52+ *
53+ * 1. dfsλ₯Ό ν΅ν΄ λͺ¨λ κ²½μ°μ μλ₯Ό ꡬνλ€.
54+ * 2. isPalindrome ν¨μλ₯Ό ν΅ν΄ ν°λ¦°λ둬μΈμ§ νμΈνλ€.
55+ *
56+ * 볡μ‘μ±
57+ *
58+ * Time Complexity: O(n^2)
59+ * Space Complexity: O(1)
60+ */
61+
62+ function isPalindrome ( s ) {
63+ let left = 0 ;
64+ let right = s . length - 1 ;
65+
66+ while ( left < right ) {
67+ if ( s [ left ] !== s [ right ] ) return false ;
68+ left ++ ;
69+ right -- ;
70+ }
71+
72+ return true ;
73+ }
74+
75+ var countSubstrings = function ( s ) {
76+ let count = 0 ;
77+
78+ function dfs ( startIdx ) {
79+ // λͺ¨λ μμμ νμ μλ£
80+ if ( startIdx === s . length ) return ;
81+
82+ // νμ¬ μμμ μμ κ°λ₯ν λͺ¨λ λμ νμΈ
83+ for ( let end = startIdx ; end < s . length ; end ++ ) {
84+ const sub = s . slice ( startIdx , end + 1 ) ;
85+ if ( isPalindrome ( sub ) ) {
86+ count ++ ;
87+ }
88+ }
89+
90+ // λ€μ μμμ μΌλ‘ μ΄λ
91+ dfs ( startIdx + 1 ) ;
92+ }
93+
94+ dfs ( 0 ) ;
95+ return count ;
96+ } ;
You canβt perform that action at this time.
0 commit comments