📌  相关文章
📜  打印使用任何一对给定的字符串形成所有可能的回文字符串

📅  最后修改于: 2021-09-03 03:36:02             🧑  作者: Mango

给定一个包含N 个单词的字符串数组arr[] ,任务是通过组合给定数组中的任意两个字符串来打印所有可能的回文字符串。

例子:

原始的方法:天真的办法是遍历所有可能的字符串对给定数组中,并检查是否字符串形式串联回文与否。如果是,则打印该对并检查下一对。

时间复杂度: O(N 2 )
辅助空间: O(1)

高效的方法:可以使用哈希优化上述方法。以下是步骤:

  1. 将所有单词存储在 Map 中,单词作为索引作为值。
  2. 对于arr[]中的每个单词(比如str ),将字符串分成字符串s1s2 ,使得s1 + s2 = str
  3. 在上述步骤之后,出现两种情况:
    • 情况 1:如果s1是回文字符串并且s2的反向存在于哈希映射中,那么我们得到所需的对( s2 的反向+当前词)。
    • 情况 2:如果s2是一个回文字符串并且如果反向s1存在于哈希映射中,那么我们得到一对(当前词+ s1 的反向)。
  4. 对数组中的所有字符串重复上述步骤。

下面是上述方法的实现:

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;
}


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


输出:
geekfkeeg
geekskeeg
abcba

时间复杂度: O(N)
辅助空间: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live