给定字符串str ,任务是重新排列给定字符串以获得最长的回文子串。
例子:
Input: str = “geeksforgeeks”
Output: eegksfskgeeor
Explanation: eegksfskgee is the longest palindromic substring after rearranging the string.
Therefore, the required output is eegksfskgeeor.
Input: str = “engineering”
Output: eginenigenr
方法:可以使用Hashing解决问题。这个想法是计算给定字符串的每个字符的频率。如果字符的发生计数超过其对所得字符串的左侧频率的1,追加一半(地板值),并在所得到的字符串的右侧剩下的一半。对于其余的字符,追加在开始或在所得到的字符串的末尾在所得字符串,其余的中间的一个字符要么。请按照以下步骤解决问题:
- 初始化一个数组,比如hash[256]来存储每个字符的频率。
- 要有效地在结果字符串的两侧附加字符,请初始化三个字符串res1、 res2和res3 。
- 该字符串RES1存储最长的回文子的左半边,RES2存储最长的回文子的右半边,而RES3卖场剩余的字符。
- 遍历hash[]数组,对于字符,比如hash[i] ,检查它的频率是否大于 1。如果发现为真,附加字符地板(散列[I] / 2)在RES1和地板(散列[I] / 2)在RES2倍。
- 否则,将不满足上述条件的第一个字符附加到res1并将所有剩余的此类字符附加到res3 。
- 最后,返回字符串res1 + reverse(res2) + res3 。
下面是上述方法的实现:
C++
// C++ program to implement
// the above approach
#include
using namespace std;
// Function to rearrange the string to
// get the longest palindromic substring
string longestPalinSub(string str) {
// Stores the length of str
int N = str.length();
// Store the count of occurrence
// of each character
int hash[256] = {0};
// Traverse the string, str
for(int i = 0; i < N;
i++) {
// Count occurrence of
// each character
hash[str[i]]++;
}
// Store the left half of the
// longest palindromic substring
string res1 = "";
// Store the right half of the
// longest palindromic substring
string res2 = "";
// Traverse the array, hash[]
for(int i = 0; i< 256; i++) {
// Append half of the
// characters to res1
for(int j = 0; j < hash[i] / 2;
j++) {
res1.push_back(i);
}
// Append half of the
// characters to res2
for(int j = (hash[i] + 1)/2;
j < hash[i]; j++) {
res2.push_back(i);
}
}
// reverse string res2 to make
// res1 + res2 palindrome
reverse(res2.begin(), res2.end());
// Store the remaining characters
string res3;
// Check If any odd character
// appended to the middle of
// the resultant string or not
bool f = false;
// Append all the character which
// occurs odd number of times
for(int i = 0; i < 256; i++) {
// If count of occurrence
// of characters is odd
if(hash[i]%2) {
if(!f) {
res1.push_back(i);
f = true;
}
else {
res3.push_back(i);
}
}
}
return (res1 + res2 + res3);
}
// Driver Code
int main() {
string str = "geeksforgeeks";
cout<
Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
// Function to rearrange the string to
// get the longest palindromic substring
static String longestPalinSub(String str)
{
// Stores the length of str
int N = str.length();
// Store the count of occurrence
// of each character
int[] hash = new int[256];
// Traverse the string, str
for(int i = 0; i < N; i++)
{
// Count occurrence of
// each character
hash[str.charAt(i)]++;
}
// Store the left half of the
// longest palindromic substring
StringBuilder res1 = new StringBuilder();
// Store the right half of the
// longest palindromic substring
StringBuilder res2 = new StringBuilder();
// Traverse the array, hash[]
for(int i = 0; i < 256; i++)
{
// Append half of the
// characters to res1
for(int j = 0; j < hash[i] / 2; j++)
{
res1.append((char)i);
}
// Append half of the
// characters to res2
for(int j = (hash[i] + 1) / 2;
j < hash[i]; j++)
{
res2.append((char)i);
}
}
// reverse string res2 to make
// res1 + res2 palindrome
StringBuilder tmp = res2.reverse();
// Store the remaining characters
StringBuilder res3 = new StringBuilder();
// Check If any odd character
// appended to the middle of
// the resultant string or not
boolean f = false;
// Append all the character which
// occurs odd number of times
for(int i = 0; i < 256; i++)
{
// If count of occurrence
// of characters is odd
if (hash[i] % 2 == 1)
{
if (!f)
{
res1.append((char)i);
f = true;
}
else
{
res3.append((char)i);
}
}
}
return (res1.toString() +
tmp.toString() +
res3.toString());
}
// Driver code
public static void main (String[] args)
{
String str = "geeksforgeeks";
System.out.println(longestPalinSub(str));
}
}
// This code is contributed by offbeat
Python3
# Python 3 program to implement
# the above approach
# Function to rearrange the
# string to get the longest
# palindromic substring
def longestPalinSub(st):
# Stores the length of
# str
N = len(st)
# Store the count of
# occurrence of each
# character
hash1 = [0] * 256
# Traverse the string,
# str
for i in range(N):
# Count occurrence of
# each character
hash1[ord(st[i])] += 1
# Store the left half of the
# longest palindromic substring
res1 = ""
# Store the right half of the
# longest palindromic substring
res2 = ""
# Traverse the array, hash[]
for i in range(256):
# Append half of the
# characters to res1
for j in range(hash1[i] // 2):
res1 += chr(i)
# Append half of the
# characters to res2
for j in range((hash1[i] + 1)//2,
hash1[i]):
res2 += chr(i)
# reverse string res2 to make
# res1 + res2 palindrome
p = list(res2)
p.reverse()
res2 = ''.join(p)
# Store the remaining characters
res3 = ""
# Check If any odd character
# appended to the middle of
# the resultant string or not
f = False
# Append all the character which
# occurs odd number of times
for i in range(256):
# If count of occurrence
# of characters is odd
if(hash1[i] % 2):
if(not f):
res1 += chr(i)
f = True
else:
res3 += chr(i)
return (res1 + res2 + res3)
# Driver Code
if __name__ == "__main__":
st = "geeksforgeeks"
print(longestPalinSub(st))
# This code is contributed by Chitranayal
C#
// C# program to implement
// the above approach
using System;
using System.Text;
class GFG{
// Reverse string
static String reverse(String input)
{
char[] a = input.ToCharArray();
int l, r = a.Length - 1;
for (l = 0; l < r; l++, r--)
{
char temp = a[l];
a[l] = a[r];
a[r] = temp;
}
return String.Join("", a);
}
// Function to rearrange the string to
// get the longest palindromic substring
static String longestPalinSub(String str)
{
// Stores the length of str
int N = str.Length;
// Store the count of occurrence
// of each character
int[] hash = new int[256];
// Traverse the string, str
for(int i = 0; i < N; i++)
{
// Count occurrence of
// each character
hash[str[i]]++;
}
// Store the left half of the
// longest palindromic substring
StringBuilder res1 = new StringBuilder();
// Store the right half of the
// longest palindromic substring
StringBuilder res2 = new StringBuilder();
// Traverse the array, hash[]
for(int i = 0; i < 256; i++)
{
// Append half of the
// characters to res1
for(int j = 0; j < hash[i] / 2; j++)
{
res1.Append((char)i);
}
// Append half of the
// characters to res2
for(int j = (hash[i] + 1) / 2;
j < hash[i]; j++)
{
res2.Append((char)i);
}
}
// reverse string res2 to make
// res1 + res2 palindrome
String tmp = reverse(res2.ToString());
// Store the remaining characters
StringBuilder res3 = new StringBuilder();
// Check If any odd character
// appended to the middle of
// the resultant string or not
bool f = false;
// Append all the character which
// occurs odd number of times
for(int i = 0; i < 256; i++)
{
// If count of occurrence
// of characters is odd
if (hash[i] % 2 == 1)
{
if (!f)
{
res1.Append((char)i);
f = true;
}
else
{
res3.Append((char)i);
}
}
}
return (res1.ToString() +
tmp.ToString() +
res3.ToString());
}
// Driver code
public static void Main(String[] args)
{
String str = "geeksforgeeks";
Console.WriteLine(longestPalinSub(str));
}
}
// This code is contributed by Rajput-Ji
Javascript
输出
eegksfskgeeor
时间复杂度: O(N)
辅助空间: O(1)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。