Skip to content

Commit 135fa6e

Browse files
committed
solved2: countSubstrings
1 parent 6e87588 commit 135fa6e

File tree

1 file changed

+49
-1
lines changed

1 file changed

+49
-1
lines changed

β€Žpalindromic-substrings/jangwonyoon.jsβ€Ž

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
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+
};

0 commit comments

Comments
Β (0)