반응형
문제
Given a string s, return the longest palindromic substring in s.
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.
https://leetcode.com/problems/longest-palindromic-substring/
풀이
회문인지 조사할 중심점을 잡아서, 중심점이 홀수 일 때와 짝수 일 때를 나눠서 길이를 비교하도록 했다.
for문이나 while문 하나로 할 수 있는 방법이 없나 고민해봤으나, 현재로써는 이 방법이 최선인 듯 하다.
코드
class Solution {
public String longestPalindrome(String s) {
String res = new String();
int maxLen = 0;
for(int i = 0; i < s.length(); i++) {
int len = Math.max(find(s, i, i), find(s, i, i+1));
if(len >= maxLen) {
res = s.substring(i - (len / 2), i + (len / 2) + (len % 2) + 1);
maxLen = len;
}
}
return res;
}
public int find(String s, int left, int right) {
int start = 0, end = 0;
while(left >= 0 && right < s.length()) {
if(s.charAt(left) == s.charAt(right)) {
start = left;
end = right;
left--;
right++;
continue;
}
break;
}
return end - start;
}
}
결과
Runtime: 50 ms, faster than 61.16% of Java online submissions for Longest Palindromic Substring.
Memory Usage: 45.2 MB, less than 39.24% of Java online submissions for Longest Palindromic Substring.
반응형
'LeetCode' 카테고리의 다른 글
7. Reverse Integer (0) | 2024.11.10 |
---|---|
6. Zigzag Conversion (1) | 2024.11.05 |
4. Median of Two Sorted Arrays (0) | 2022.02.06 |
3. Longest Substring Without Repeating Characters 수정 (0) | 2022.01.21 |
3. Longest Substring Without Repeating Characters (0) | 2022.01.16 |