알고리즘/LeetCode
LeetCode - 5. Longest Palindromic Substring
시나모온
2021. 10. 16. 00:57
문제 링크입니다 : https://leetcode.com/problems/longest-palindromic-substring/
Longest Palindromic Substring - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
C++
class Solution {
public:
string longestPalindrome(string s) {
string result = "";
int maxLength = 0;
if (s.size() == 1) {
return s;
}
for (int i = 0; i < s.size() - 1; i++) {
int leftIndex = i;
int rightIndex = i;
int cnt = 1;
while (true) {
leftIndex--;
rightIndex++;
if (leftIndex < 0 || rightIndex == s.size() || s[leftIndex] != s[rightIndex]) {
if (cnt > maxLength) {
maxLength = cnt;
result = s.substr(leftIndex + 1, rightIndex - leftIndex - 1);
}
break;
}
cnt += 2;
}
leftIndex = i;
rightIndex = i + 1;
cnt = 0;
while (true) {
if (leftIndex < 0 || rightIndex == s.size() || s[leftIndex] != s[rightIndex]) {
if (cnt > maxLength) {
maxLength = cnt;
result = s.substr(leftIndex + 1, rightIndex - leftIndex - 1);
}
break;
}
cnt += 2;
leftIndex--;
rightIndex++;
}
}
return result;
}
};
JAVA
class Solution {
public String longestPalindrome(String s) {
String result = "";
int maxLength = 0;
if (s.length() == 1) {
return s;
}
for (int i = 0; i < s.length() - 1; i++) {
int leftIndex = i;
int rightIndex = i;
int cnt = 1;
while(true) {
leftIndex--;
rightIndex++;
if (leftIndex < 0 || rightIndex == s.length() || s.charAt(leftIndex) != s.charAt(rightIndex)) {
if (cnt > maxLength) {
maxLength = cnt;
result = s.substring(leftIndex + 1, rightIndex);
}
break;
}
cnt += 2;
}
leftIndex = i;
rightIndex = i + 1;
cnt = 0;
while(true) {
if (leftIndex < 0 || rightIndex == s.length() || s.charAt(leftIndex) != s.charAt(rightIndex)) {
if (cnt > maxLength) {
maxLength = cnt;
result = s.substring(leftIndex + 1, rightIndex);
}
break;
}
cnt += 2;
leftIndex--;
rightIndex++;
}
}
return result;
}
}
Python3
class Solution:
def longestPalindrome(self, s: str) -> str:
result = ''
maxLen = 0
s_len = len(s)
if s_len == 1:
return s
for i in range(s_len - 1):
left_index = i
right_index = i
cnt = 1
while True:
left_index -= 1
right_index += 1
if left_index < 0 or right_index == s_len or s[left_index] != s[right_index]:
if cnt > maxLen:
maxLen = cnt
result = s[left_index + 1 : right_index]
break
cnt += 2
left_index = i
right_index = i + 1
cnt = 0
while True:
if left_index < 0 or right_index == s_len or s[left_index] != s[right_index]:
if cnt > maxLen:
maxLen = cnt
result = s[left_index + 1 : right_index]
break
left_index -= 1
right_index += 1
cnt += 2
return result
개발 환경 : vscode
지적, 조언, 질문 환영입니다! 댓글 남겨주세요~