Skip to content

Commit 6a8a17f

Browse files
(Leetcode) 647 - Palindromic Substrings 풀이
1 parent f8b6b9b commit 6a8a17f

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

_posts/2024-07-08-leetcode-647.md

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
---
2+
layout: post
3+
title: (Leetcode) 647 - Palindromic Substrings 풀이
4+
categories: [스터디-알고리즘]
5+
tags: [자바, java, 리트코드, Leetcode, 알고리즘, array, pointer]
6+
date: 2024-07-08 16:00:00 +0900
7+
toc: true
8+
---
9+
10+
기회가 되어 [달레님의 스터디](https://github.com/DaleStudy/leetcode-study)에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다.
11+
12+
[https://neetcode.io/practice](https://neetcode.io/practice)
13+
14+
---
15+
16+
[https://leetcode.com/problems/palindromic-substrings/description/](https://leetcode.com/problems/palindromic-substrings/description/)
17+
18+
## 내가 작성한 풀이
19+
20+
Longest Palindromic Substring 문제를 풀어본 적이 있다면 보너스 문제같은 느낌이다. ([문제](https://leetcode.com/problems/longest-palindromic-substring), [풀이](https://algorithm.jonghoonpark.com/2024/07/01/leetcode-5))
21+
약간만 수정해주면 바로 풀린다.
22+
23+
포인터 `i`를 이용하여 각 위치에서의 palindromic substring 을 모두 계산해주면 된다.
24+
25+
```java
26+
class Solution {
27+
public int countSubstrings(String s) {
28+
int count = 0;
29+
30+
char[] charArray = s.toCharArray();
31+
for (int i = 0; i < s.length(); i++) {
32+
char currentChar = charArray[i];
33+
count++;
34+
35+
int left = i;
36+
int right = i;
37+
38+
while (right < s.length() - 1 && currentChar == charArray[right + 1]) {
39+
right++;
40+
count++;
41+
}
42+
43+
while (left > 0 && right < s.length() - 1 && charArray[left - 1] == charArray[right + 1]) {
44+
left--;
45+
right++;
46+
count++;
47+
}
48+
}
49+
50+
return count;
51+
}
52+
}
53+
```
54+
55+
### TC, SC
56+
57+
시간 복잡도는 평균적으로 O(n)이다. palindrome 의 길이가 n 에 가까워질수록 시간 복잡도는 O(n^2) 에 가까워 진다.
58+
공간 복잡도는 O(n)이다.

0 commit comments

Comments
 (0)