Skip to content

Commit

Permalink
add: solve DaleStudy#267 Palindromic Substrings with ts
Browse files Browse the repository at this point in the history
  • Loading branch information
Yjason-K committed Jan 1, 2025
1 parent faf89d9 commit bf38b87
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions palindromic-substrings/Yjason-K.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* ๋ฌธ์ž์—ด์—์„œ substring ์ค‘ panlindrome์ธ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ•จ์ˆ˜
* @param {string} s - ์ž…๋ ฅ ๋ฌธ์ž์—ด
* @returns {number} - s๋ฌธ์ž์—ด์—์„œ ์ฐพ์„์ˆ˜ ์žˆ๋Š” panlindrome substring์˜ ๊ฐœ์ˆ˜
*
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n^2) (n: ๋ฌธ์ž์—ด ๊ธธ์ด)
* - ํ•œ ๋ฒˆ์˜ ์™ธ๋ถ€ ๋ฃจํ”„: ๋ถ€๋ถ„ ๋ฌธ์ž์—ด ๊ธธ์ด (\(subLen\)) - O(n)
* - ๋‚ด๋ถ€ ๋ฃจํ”„: ์‹œ์ž‘ ์ธ๋ฑ์Šค (\(start\)) - O(n)
* - ๋”ฐ๋ผ์„œ, ์ด ๋ณต์žก๋„๋Š” O(n^2)
*
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(n^2)
* - DP ๋ฐฐ์—ด dp[i][j]๋Š” \(n^2\) ํฌ๊ธฐ๋ฅผ ๊ฐ€์ง€๋ฉฐ ๋ฌธ์ž์—ด์˜ ๋ชจ๋“  ์‹œ์ž‘๊ณผ ๋ ์กฐํ•ฉ์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.
*/
function countSubstrings(s: string): number {
const n = s.length; // ๋ฌธ์ž์—ด ๊ธธ์ด
let result = 0;

// DP ๋ฐฐ์—ด ์ƒ์„ฑ (dp[i][j] ๋Š” s[i] ~ s[j] ๊นŒ์ง€๊ฐ€ ํšŒ๋ฌธ์ธ์ง€ ์—ฌ๋ถ€๋ฅผ ์ €์žฅ)
const dp: boolean[][] = Array.from({ length: n }, () => Array(n).fill(false));

// 1๊ธ€์ž ๊ฒฝ์šฐ
for (let i = 0; i < n; i++) {
dp[i][i] = true;
result++;
}

// 2๊ธ€์ž ๊ฒฝ์šฐ
for (let i = 0; i < n - 1; i++) {
if (s[i] === s[i + 1]) {
dp[i][i + 1] = true;
result++;
}
}

// 3๊ธ€์ž ์ด์ƒ์ธ ๊ฒฝ์šฐ
for (let subLen = 3; subLen <= n; subLen++) {
for (let start = 0; start <= n - subLen; start++) {
const end = start + subLen - 1;
// ์–‘ ๋ ๋ฌธ์ž๊ฐ€ ๊ฐ™๊ณ , ๋‚ด๋ถ€ ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์ด ํšŒ๋ฌธ์ด๋ฉด true
if (s[start] === s[end] && dp[start + 1][end - 1]) {
dp[start][end] = true;
result++;
}
}
}

return result;
}

0 comments on commit bf38b87

Please sign in to comment.