반응형
SMALL
문제
Given a string s, return the longest palindromic substring in s.
A string is called a palindrome string if the reverse of that string is the same as the original string.
Example 1:
Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd"
Output: "bb"
Constraints:
- 1 <= s.length <= 1000
- s consist of only digits and English letters.
코드
/**
* @param {string} s
* @return {string}
*/
var longestPalindrome = function(s) {
let longest = '';
const generate = (x, y) => {
while(x >= 0 && y < s.length && s[x] === s[y]) {
x--;
y++;
}
// 만약 x가 -1 일 때, 혹은 만약 y가 s.length + 1일 때를 반영
return s.slice(x + 1, y);
}
for(let i = 0; i < s.length; i++) {
// 홀수인 부분을 돈다
let stringOdd = generate(i, i);
// 짝수인 부분을 돈다
let stringEven = generate(i, i + 1);
let palindrome = stringOdd.length > stringEven.length ? stringOdd : stringEven;
if(palindrome.length > longest.length) {
longest = palindrome
}
}
return longest
}
반응형
LIST
'Coding Interview' 카테고리의 다른 글
[LeetCode] DFS, DP 322. Coin Change (1) | 2022.10.04 |
---|---|
[LeetCode] DP, DFS - 22. Generate Parentheses (0) | 2022.10.04 |
[LeetCode] DP - 53. Maximum Subarray (0) | 2022.10.01 |
알고리즘 유형을 알아보자 (0) | 2022.10.01 |
[LeetCode] DP - 42. Trapping Rain Water (0) | 2022.10.01 |