给定一个包含N 个单词的字符串数组arr[] ,任务是通过组合给定数组中的任意两个字符串来打印所有可能的回文字符串。
例子:
Input: arr[] = [“geekf”, “geeks”, “or”, “keeg”, “abc”, “ba”]
Output: [“geekfkeeg”, “geekskeeg”, “abcba”]
Explanation:
Below pairs forms the palindromic string on combining:
1. “geekf” + “keeg” = “geekfkeeg”
2. “geeks” + “keeg” = “geekskeeg”
3. “abc” + “ba” = “abcba”
Input: arr[] = [“dcb”, “yz”, “xy”, “efg”, “yx”]
Output: [“xyyx”, “yxxy”]
Explanation:
1. “xy” + “yz” = “xyyz”
2. “yx” + “xy” = “yxxy”
原始的方法:天真的办法是遍历所有可能的字符串对给定数组中,并检查是否字符串形式串联回文与否。如果是,则打印该对并检查下一对。
时间复杂度: O(N 2 )
辅助空间: O(1)
高效的方法:可以使用哈希优化上述方法。以下是步骤:
- 将所有单词存储在 Map 中,单词作为键,索引作为值。
- 对于arr[]中的每个单词(比如str ),将字符串分成字符串s1和s2 ,使得s1 + s2 = str 。
- 在上述步骤之后,出现两种情况:
- 情况 1:如果s1是回文字符串并且s2的反向存在于哈希映射中,那么我们得到所需的对( s2 的反向+当前词)。
- 情况 2:如果s2是一个回文字符串并且如果反向s1存在于哈希映射中,那么我们得到一对(当前词+ s1 的反向)。
- 对数组中的所有字符串重复上述步骤。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to check whether the string
// word is palindrome or not
bool ispalin(string word)
{
if (word.length() == 1
|| word.empty()) {
return true;
}
int l = 0;
int r = word.length() - 1;
// Iterate word
while (l <= r) {
if (word[l] != word[r]) {
return false;
}
l++;
r--;
}
return true;
}
// Function to find the palindromicPairs
vector
palindromicPairs(vector& words)
{
vector output;
if (words.size() == 0
|| words.size() == 1) {
return output;
}
// Insert all the strings with
// their indices in the hash map
unordered_map mp;
for (int i = 0; i < words.size(); i++) {
mp[words[i]] = i;
}
// Iterate over all the words
for (int i = 0; i < words.size(); i++) {
// If the word is empty then
// we simply pair it will all the
// words which are palindrome
// present in the array
// except the word itself
if (words[i].empty()) {
for (auto x : mp) {
if (x.second == i) {
continue;
}
if (ispalin(x.first)) {
output.push_back(x.first);
}
}
}
// Create all possible substrings
// s1 and s2
for (int j = 0;
j < words[i].length(); j++) {
string s1 = words[i].substr(0, j + 1);
string s2 = words[i].substr(j + 1);
// Case 1
// If s1 is palindrome and
// reverse of s2 is
// present in hashmap at
// index other than i
if (ispalin(s1)) {
reverse(s2.begin(),
s2.end());
string temp = s2;
if (mp.count(s2) == 1
&& mp[s2] != i) {
string ans = s2 + words[i];
output.push_back(ans);
}
s2 = temp;
}
// Case 2
// If s2 is palindrome and
// reverse of s1 is
// present in hashmap
// at index other than i
if (ispalin(s2)) {
string temp = s1;
reverse(s1.begin(),
s1.end());
if (mp.count(s1) == 1
&& mp[s1] != i) {
string ans = words[i] + s1;
output.push_back(ans);
}
s1 = temp;
}
}
}
// Return output
return output;
}
// Driver Code
int main()
{
vector words;
// Given array of words
words = { "geekf", "geeks", "or",
"keeg", "abc", "ba" };
// Function call
vector result
= palindromicPairs(words);
// Print the palindromic strings
// after combining them
for (auto x : result) {
cout << x << endl;
}
return 0;
}
Java
// Java program for the above approach
import java.util.*;
public class Main
{
// Function to check whether the string
// word is palindrome or not
static boolean ispalin(String word)
{
if (word.length() == 1
|| word.length() == 0) {
return true;
}
int l = 0;
int r = word.length() - 1;
// Iterate word
while (l <= r) {
if (word.charAt(l) != word.charAt(r)) {
return false;
}
l++;
r--;
}
return true;
}
// Function to find the palindromicPairs
static Vector palindromicPairs(String[] words)
{
Vector output = new Vector();
if (words.length == 0 ||
words.length == 1)
{
return output;
}
// Insert all the strings with
// their indices in the hash map
HashMap mp = new HashMap<>();
for (int i = 0; i < words.length; i++) {
mp.put(words[i], i);
}
// Iterate over all the words
for(int i = 0; i < words.length; i++)
{
// If the word is empty then
// we simply pair it will all the
// words which are palindrome
// present in the array
// except the word itself
if ((words[i]).length() == 0)
{
for(Map.Entry key : mp.entrySet())
{
if (key.getValue() == i)
{
continue;
}
if (ispalin(key.getKey()))
{
output.add(key.getKey());
}
}
}
// Create all possible substrings
// s1 and s2
for(int j = 0; j < words[i].length(); j++)
{
String s1 = words[i].substring(0, j + 1);
String s2 = words[i].substring(j + 1);
// Case 1
// If s1 is palindrome and
// reverse of s2 is
// present in hashmap at
// index other than i
if (ispalin(s1))
{
StringBuffer arr = new StringBuffer(s2);
arr.reverse();
s2 = new String(arr);
String temp = s2;
if (mp.containsKey(s2) && mp.get(s2) != i)
{
String ans = s2 + words[i];
output.add(ans);
}
s2 = temp;
}
// Case 2
// If s2 is palindrome and
// reverse of s1 is
// present in hashmap
// at index other than i
if (ispalin(s2))
{
String temp = s1;
StringBuffer arr = new StringBuffer(s1);
arr.reverse();
s1 = new String(arr);
if (mp.containsKey(s1) && mp.get(s1) != i)
{
String ans = words[i] + s1;
output.add(ans);
}
s1 = temp;
}
}
}
// Return output
return output;
}
public static void main(String[] args) {
String[] words = { "geekf", "geeks", "or", "keeg", "abc", "ba" };
// Function call
Vector result = palindromicPairs(words);
// Print the palindromic strings
// after combining them
for(String x : result)
System.out.println(x);
}
}
// This code is contributed by mukesh07.
Python3
# Python3 program for the above approach
# Function to check whether the string
# word is palindrome or not
def ispalin(word):
if (len(word) == 1 or len(word)):
return True
l = 0
r = len(word) - 1
# Iterate word
while (l <= r):
if (word[l] != word[r]):
return False
l+= 1
r-= 1
return True
# Function to find the palindromicPairs
def palindromicPairs(words):
output = []
if (len(words) == 0 or len(words) == 1):
return output
# Insert all the strings with
# their indices in the hash map
mp = {}
for i in range(len(words)):
mp[words[i]] = i
# Iterate over all the words
for i in range(len( words)):
# If the word is empty then
# we simply pair it will all the
# words which are palindrome
# present in the array
# except the word itself
if (len(words[i]) == 0):
for x in mp:
if (mp[x] == i):
continue
if (ispalin(x)):
output.append(x)
# Create all possible substrings
# s1 and s2
for j in range (len(words[i])):
s1 = words[i][0 : j + 1]
s2 = words[i][j + 1 : ]
# Case 1
# If s1 is palindrome and
# reverse of s2 is
# present in hashmap at
# index other than i
if (ispalin(s1)):
p = list(s2)
p.reverse()
s2 = ''.join(p)
temp = s2;
if (s2 in mp and mp[s2] != i):
ans = s2 + words[i]
output.append(ans)
s2 = temp
# Case 2
# If s2 is palindrome and
# reverse of s1 is
# present in hashmap
# at index other than i
if (ispalin(s2)):
temp = s1
p = list(s1)
p.reverse()
s1 = ''.join(p)
if (s1 in mp and mp[s1] != i):
ans = words[i] + s1
output.append(ans)
s1 = temp
# Return output
return output
# Driver Code
if __name__ == "__main__":
# Given array of words
words = [ "geekf", "geeks", "or",
"keeg", "abc", "ba" ]
# Function call
result = palindromicPairs(words);
# Print the palindromic strings
# after combining them
for x in result:
print(x)
# This code is contributed by chitranayal
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
// Function to check whether the string
// word is palindrome or not
static bool ispalin(string word)
{
if (word.Length == 1
|| word.Length == 0) {
return true;
}
int l = 0;
int r = word.Length - 1;
// Iterate word
while (l <= r) {
if (word[l] != word[r]) {
return false;
}
l++;
r--;
}
return true;
}
// Function to find the palindromicPairs
static List palindromicPairs(string[] words)
{
List output = new List();
if (words.Length == 0 ||
words.Length == 1)
{
return output;
}
// Insert all the strings with
// their indices in the hash map
Dictionary mp = new Dictionary();
for (int i = 0; i < words.Length; i++) {
mp[words[i]] = i;
}
// Iterate over all the words
for(int i = 0; i < words.Length; i++)
{
// If the word is empty then
// we simply pair it will all the
// words which are palindrome
// present in the array
// except the word itself
if (words[i].Length == 0)
{
foreach(KeyValuePair key in mp)
{
if (key.Value == i)
{
continue;
}
if (ispalin(key.Key))
{
output.Add(key.Key);
}
}
}
// Create all possible substrings
// s1 and s2
for(int j = 0; j < words[i].Length; j++)
{
string s1 = words[i].Substring(0, j + 1);
string s2 = words[i].Substring(j + 1);
// Case 1
// If s1 is palindrome and
// reverse of s2 is
// present in hashmap at
// index other than i
if (ispalin(s1))
{
char[] arr = s2.ToCharArray();
Array.Reverse(arr);
s2 = new string(arr);
string temp = s2;
if (mp.ContainsKey(s2) && mp[s2] != i)
{
string ans = s2 + words[i];
output.Add(ans);
}
s2 = temp;
}
// Case 2
// If s2 is palindrome and
// reverse of s1 is
// present in hashmap
// at index other than i
if (ispalin(s2))
{
string temp = s1;
char[] arr = s1.ToCharArray();
Array.Reverse(arr);
s1 = new string(arr);
if (mp.ContainsKey(s1) && mp[s1] != i)
{
string ans = words[i] + s1;
output.Add(ans);
}
s1 = temp;
}
}
}
// Return output
return output;
}
static void Main()
{
string[] words = { "geekf", "geeks", "or", "keeg", "abc", "ba" };
// Function call
List result = palindromicPairs(words);
// Print the palindromic strings
// after combining them
foreach(string x in result) {
Console.WriteLine(x);
}
}
}
// This code is contributed by rameshtravel07.
Javascript
geekfkeeg
geekskeeg
abcba
时间复杂度: O(N)
辅助空间: O(N)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。