Skip to content

Commit 7ff0704

Browse files
committed
WEEK 01 Palindromic Substrings Feedback
1 parent e55594c commit 7ff0704

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

palindromic-substrings/sunjae95.js

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,3 +88,77 @@ var countSubstrings = function (s) {
8888

8989
return answer.length;
9090
};
91+
92+
/**
93+
* @description
94+
* WEEK 01 Feedback
95+
* 1. remove slice and change to endpoint
96+
* 2. kadane's algorithm
97+
*
98+
* time complexity: O(N^3)
99+
* space complexity: O(1)
100+
*
101+
* result
102+
* solution 1 apply
103+
*/
104+
var countSubstrings = function (s) {
105+
let answer = 0;
106+
const len = s.length;
107+
108+
for (let startIndex = 0; startIndex < len; startIndex++) {
109+
let subStr = "";
110+
let isSubPalindromic = true;
111+
answer++;
112+
113+
for (let endIndex = startIndex + 1; endIndex < len; endIndex++) {
114+
if (isSubPalindromic && s[startIndex] === s[endIndex]) answer++;
115+
subStr += s[endIndex];
116+
isSubPalindromic = isPalindromic(subStr);
117+
}
118+
}
119+
120+
return answer;
121+
};
122+
123+
function isPalindromic(str) {
124+
const len = str.length;
125+
const middleIndex = Math.floor(len / 2);
126+
127+
for (let i = 0; i < middleIndex; i++) {
128+
if (str[i] !== str[len - 1 - i]) return false;
129+
}
130+
131+
return true;
132+
}
133+
/**
134+
* @description
135+
* WEEK 01 Feedback
136+
* 1. remove slice and change to endpoint
137+
* 2. kadane's algorithm
138+
*
139+
* time complexity: O(N^2)
140+
* space complexity: O(1)
141+
*
142+
* result
143+
* solve 3(https://www.algodale.com/problems/palindromic-substrings/) include 1,2 solution
144+
*/
145+
var countSubstrings = function (s) {
146+
let count = 0;
147+
const len = s.length;
148+
149+
for (let i = 0; i < len; i++) {
150+
let [start, end] = [i, i];
151+
152+
while (s[start] === s[end] && start >= 0 && end < len) {
153+
count++;
154+
[start, end] = [start - 1, end + 1];
155+
}
156+
[start, end] = [i, i + 1];
157+
while (s[start] === s[end] && start >= 0 && end < len) {
158+
count++;
159+
[start, end] = [start - 1, end + 1];
160+
}
161+
}
162+
163+
return count;
164+
};

0 commit comments

Comments
 (0)