Palindrome
1. ๊ฐ๋
Palindrome์ ๊ฑฐ๊พธ๋ก ์ฝ์ด๋ ์ ๋๋ก ์ฝ๋ ๊ฒ๊ณผ ๊ฐ์ ๋ฌธ์ฅ์ ๋งํ๋ค.
2. ๋ฌธ์
https://leetcode.com/problems/palindrome-partitioning/description/
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
vector<vector<string>> answer;
vector<string> sub;
vector<vector<string>> partition(string s) {
dfs(s, 0);
return answer;
}
void dfs(string s, int index) {
if (index == s.length()) {
answer.push_back(sub);
return;
}
for (int i = index; i < s.length(); i++) {
string substr = s.substr(index, i - index + 1);
if (!palindrome(substr))
continue;
sub.push_back(substr);
dfs(s, i + 1);
sub.pop_back();
}
}
bool palindrome(string s) {
int size = s.length();
for (int i = 0; i < size / 2; i++)
if (s[i] != s[size - i - 1])
return false;
return true;
}
};
https://leetcode.com/problems/longest-palindromic-substring/description/
#include <string>
using namespace std;
class Solution {
public:
bool dp[1001][1001]{};
string longestPalindrome(string s) {
// 1๊ธ์
string answer = s.substr(0, 1);
for (int i = 0; i < s.size(); i++)
dp[i][i] = true;
// 2๊ธ์
for (int i = 0; i < s.size() - 1; i++)
if (s[i] == s[i + 1]) {
dp[i][i + 1] = true;
answer = s.substr(i, 2);
}
// 3๊ธ์ ์ด์
for (int i = 3; i <= s.size(); i++)
for (int j = 0; j + i <= s.size(); j++)
if (dp[j + 1][j + i - 2] && s[j] == s[j + i - 1]) {
dp[j][j + i - 1] = true;
if (answer.size() < i)
answer = s.substr(j, i);
}
return answer;
}
};
https://leetcode.com/problems/shortest-palindrome/description/
#include <string>
using namespace std;
class Solution {
public:
string shortestPalindrome(string s)
{
int i = 0, n = s.size();
for (int j = n - 1; j >= 0; --j)
if (s[i] == s[j])
++i;
if (i == n)
return s;
string add = s.substr(i); // ์ถ๊ฐํด์ผ ํ ์ต์ ๋ฌธ์์ด
reverse(add.begin(), add.end());
return add + shortestPalindrome(s.substr(0, i)) + s.substr(i);
}
};