Skip to content

Commit b4eb4ca

Browse files
authored
Merge pull request #1901 from jangwonyoon/main
[jangwonyoon] WEEK 8 Solutions
2 parents 0ab1e65 + 135fa6e commit b4eb4ca

File tree

1 file changed

+96
-0
lines changed

1 file changed

+96
-0
lines changed
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
/**
2+
* @param {string} s
3+
* @return {number}
4+
*
5+
* 풀이 방법 1
6+
*
7+
* 1. brute force λ₯Ό μ‚¬μš©ν•΄μ„œ λͺ¨λ“  경우의 수λ₯Ό κ΅¬ν•œλ‹€.
8+
* 2. νˆ¬ν¬μΈν„°λ₯Ό 톡해 isPalindrome 을 ν™•μΈν•œλ‹€.
9+
*
10+
* λ³΅μž‘μ„±
11+
*
12+
* Time Complexity: O(n^2)
13+
* Space Complexity: O(1)
14+
*/
15+
16+
/**
17+
* isPalindrome ν•¨μˆ˜
18+
*/
19+
function isPalindrome(s) {
20+
let left = 0;
21+
let right = s.length - 1;
22+
23+
while (left < right) {
24+
if (s[left] !== s[right]) return false;
25+
left++;
26+
right--;
27+
}
28+
29+
return true;
30+
}
31+
32+
var countSubstrings = function(s) {
33+
let count = 0;
34+
35+
// λͺ¨λ“  경우의 수λ₯Ό κ΅¬ν•œλ‹€.
36+
for (let start = 0; start < s.length; start++) {
37+
for (let end = start; end < s.length; end++) {
38+
const subStr = s.slice(start, end + 1);
39+
40+
// isPalindrome ν•¨μˆ˜λ₯Ό 톡해 νŒ°λ¦°λ“œλ‘¬μΈμ§€ ν™•μΈν•œλ‹€.
41+
if (isPalindrome(subStr)) {
42+
count++;
43+
}
44+
}
45+
}
46+
47+
return count;
48+
};
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)