728x90
반응형
https://leetcode.com/problems/longest-palindromic-substring/description/
문제
문제 분석
- 문자열을 직접 잘라서 하나씩 조사하는 것보다 포인터를 두 개를 두어서 중심을 기준으로 늘려가는 것이 효율적이라고 판단하였다.
풀이
class Solution {
private:
string origin;
int length;
string expand(int left, int right){
while (left >= 0 && right < length && origin[left] == origin[right]){
left--;
right++;
}
return origin.substr(left + 1, right - left - 1);
}
public:
string longestPalindrome(string s) {
origin = s;
length = s.length();
string result = "";
string temp_1;
string temp_2;
if(length == 1){
return s;
}
for(int i = 0; i < length - 1; i++){
temp_1 = expand(i, i+1);
temp_2 = expand(i, i+2);
if (temp_1.length() >= temp_2.length()){
if(temp_1.length() >= result.length())
result = temp_1;
}else{
if(temp_2.length() >= result.length())
result = temp_2;
}
}
return result;
}
};
- 실수했었던 점: substr이 파이썬과 같이 범위들을 지정하는 것인줄 알았는데, (시작 위치, 개수)여서 제대로 된 결과를 얻디 못했었다.
728x90
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
[LeetCode] C++ 42. Trapping Rain Water (0) | 2024.08.12 |
---|---|
[LeetCode] C++ 1. Two Sum (0) | 2024.08.05 |
[LeetCode] C++ 49. Group Anagrams (0) | 2024.08.02 |
[LeetCode] C++ 819. Most Common Word (0) | 2024.08.02 |
[LeetCode] C++ 937. Reorder Data in Log Files (0) | 2024.08.02 |