|
| 1 | +/** |
| 2 | + * @description |
| 3 | + * time complexity: O(N^3) |
| 4 | + * space complexity: O(N) |
| 5 | + * |
| 6 | + * brainstorming: |
| 7 | + * 1. stack, permutation |
| 8 | + * 2. Brute force |
| 9 | + * |
| 10 | + * strategy: |
| 11 | + * Brute force, calculate |
| 12 | + * |
| 13 | + * reason: |
| 14 | + * intuitive way |
| 15 | + * |
| 16 | + * @param {string} s |
| 17 | + * @return {number} |
| 18 | + */ |
| 19 | +var countSubstrings = function (s) { |
| 20 | + let answer = 0; |
| 21 | + const len = s.length; |
| 22 | + |
| 23 | + for (let i = 0; i < len; i++) { |
| 24 | + for (let j = i + 1; j < len + 1; j++) { |
| 25 | + const subStr = s.slice(i, j); |
| 26 | + if (isPalindrome(subStr)) answer++; |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + return answer; |
| 31 | +}; |
| 32 | + |
| 33 | +function isPalindrome(str) { |
| 34 | + const len = str.length; |
| 35 | + const middleIndex = Math.floor(len / 2); |
| 36 | + |
| 37 | + for (let i = 0; i < middleIndex; i++) { |
| 38 | + if (str[i] !== str[len - 1 - i]) return false; |
| 39 | + } |
| 40 | + |
| 41 | + return true; |
| 42 | +} |
| 43 | + |
| 44 | +/** |
| 45 | + * @description |
| 46 | + * time complexity: O(N^2) |
| 47 | + * space complexity: O(N^2) |
| 48 | + * |
| 49 | + * brainstorming: |
| 50 | + * 1. https://sbslc.tistory.com/56 |
| 51 | + * |
| 52 | + * strategy: |
| 53 | + * dynamic programming |
| 54 | + * |
| 55 | + * reason: |
| 56 | + * to challenge dp |
| 57 | + * |
| 58 | + * @param {string} s |
| 59 | + * @return {number} |
| 60 | + */ |
| 61 | +var countSubstrings = function (s) { |
| 62 | + const answer = []; |
| 63 | + const MAX_LENGTH = s.length; |
| 64 | + const dp = Array.from({ length: MAX_LENGTH }, (_, i) => |
| 65 | + Array.from({ length: MAX_LENGTH }, (_, j) => { |
| 66 | + if (i === j) answer.push(s[i]); |
| 67 | + return i === j; |
| 68 | + }) |
| 69 | + ); |
| 70 | + // Check next step ex) aa, bb, cc |
| 71 | + for (let i = 0; i < MAX_LENGTH - 1; i++) { |
| 72 | + const nextIndex = i + 1; |
| 73 | + if (s[i] === s[nextIndex]) { |
| 74 | + dp[i][nextIndex] = true; |
| 75 | + answer.push(s.slice(i, nextIndex + 1)); |
| 76 | + } |
| 77 | + } |
| 78 | + // Check against values calculated in the previous step |
| 79 | + for (let len = 2; len <= MAX_LENGTH; len++) { |
| 80 | + for (let i = 0; i < MAX_LENGTH - len; i++) { |
| 81 | + const lastIndex = len + i; |
| 82 | + if (s[i] === s[lastIndex] && dp[i + 1][lastIndex - 1]) { |
| 83 | + dp[i][lastIndex] = true; |
| 84 | + answer.push(s.slice(i, lastIndex + 1)); |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + return answer.length; |
| 90 | +}; |
0 commit comments