📌  相关文章
📜  对字符串,其串接的计数形成回文字符串

📅  最后修改于: 2021-10-28 01:35:01             🧑  作者: Mango

给定一个由N 个字符串组成的数组A[ ] ,任务是计算在合并时形成回文字符串或可以重新排列以形成回文字符串的可能字符串对的数量。

例子 :

天真的方法:
解决这个问题最简单的方法是从给定的数组中生成所有可能的对并合并这些对以生成新的字符串。对于每一个这种合并字符串,产生该字符串的所有可能的排列和每个置换,检查它是否是一个回文字符串或不并相应地增加计数。
时间复杂度: O(N 2 * L! * L),其中 L 是字符串的最大长度。
辅助空间: O(M)

有效的方法:
最多一个字符出现奇数,其余每个字符偶数出现时总是可以形成回文字符串。由于允许对合并字符串中的字符进行重新排列,所以我们只需要统计合并字符串中字符出现的频率,并检查是否满足回文字符串。

因此,可以观察到以下类型的两对字符串可以合并形成一个回文字符串:

  • 两个字符串中每个字符的出现频率相同
  • 两个字符串最多一个字符具有不同的频率。

请按照以下步骤解决问题:

  • 遍历给定数组并为每个字符串存储每个字符的频率。
  • 为每个频率分配奇偶校验(01) 。为偶数频率指定0 ,为奇数频率指定1
  • 初始化一个映射来存储生成的每个频率数组的频率。
  • 由于允许重新排列,因此反转每个字符的奇偶校验并将频率数组包含在映射中。
  • 最后,返回相似频率数组的总数,这将给出所需的对数。

下面是上述方法的实现:

C++
// C++ Program to find
// palindromic string
#include 
using namespace std;
 
int getCount(int N, vector& s)
{
    // Stores frequency array
    // and its count
    map, int> mp;
 
    // Total number of pairs
    int ans = 0;
 
    for (int i = 0; i < N; i++) {
 
        // Initializing array of size 26
        // to store count of character
        vector a(26, 0);
 
        // Counting occurrence of each
        // character of current string
        for (int j = 0; j < s[i].size(); j++) {
 
            a[s[i][j] - 'a']++;
        }
 
        // Convert each count to parity(0 or 1)
        // on the basis of its frequency
        for (int j = 0; j < 26; j++) {
 
            a[j] = a[j] % 2;
        }
 
        // Adding to answer
        ans += mp[a];
 
        // Frequency of single character
        // can be possibly changed,
        // so change its parity
        for (int j = 0; j < 26; j++) {
 
            vector changedCount = a;
 
            if (a[j] == 0)
                changedCount[j] = 1;
            else
                changedCount[j] = 0;
 
            ans += mp[changedCount];
        }
 
        mp[a]++;
    }
 
    return ans;
}
 
int main()
{
    int N = 6;
    vector A
        = { "aab", "abcac", "dffe",
            "ed", "aa", "aade" };
 
    cout << getCount(N, A);
 
    return 0;
}


Java
// Java program to find
// palindromic string
import java.util.*;
 
class GFG{
 
static int getCount(int N, List s)
{
     
    // Stores frequency array
    // and its count
    Map, Integer> mp = new HashMap<>();
     
    // Total number of pairs
    int ans = 0;
     
    for(int i = 0; i < N; i++)
    {
         
        // Initializing array of size 26
        // to store count of character
        List a = new ArrayList<>(26);
        for(int k = 0; k < 26; k++)
            a.add(0);
         
        // Counting occurrence of each
        // character of current string
        for(int j = 0; j < s.get(i).length(); j++)
        {
            a.set((s.get(i).charAt(j) - 'a'),
             a.get(s.get(i).charAt(j) - 'a') + 1);
        }
 
        // Convert each count to parity(0 or 1)
        // on the basis of its frequency
        for(int j = 0; j < 26; j++)
        {
            a.set(j, a.get(j) % 2);
        }
         
        // Adding to answer
        ans += mp.getOrDefault(a, 0);
         
        // Frequency of single character
        // can be possibly changed,
        // so change its parity
        for(int j = 0; j < 26; j++)
        {
            List changedCount = new ArrayList<>();
            changedCount.addAll(a);
             
            if (a.get(j) == 0)
                changedCount.set(j, 1);
            else
                changedCount.set(j, 0);
             
            ans += mp.getOrDefault(changedCount, 0);
        }
        mp.put(a, mp.getOrDefault(a, 0) + 1);
    }
    return ans;
}
 
// Driver code
public static void main (String[] args)
{
    int N = 6;
    List A = Arrays.asList("aab", "abcac",
                                   "dffe", "ed",
                                   "aa", "aade");
     
    System.out.print(getCount(N, A));
}
}
 
// This code is contributed by offbeat


Python3
# Python3 program to find
# palindromic string
from collections import defaultdict
 
def getCount(N, s):
 
    # Stores frequency array
    # and its count
    mp = defaultdict(lambda: 0)
 
    # Total number of pairs
    ans = 0
 
    for i in range(N):
 
        # Initializing array of size 26
        # to store count of character
        a = [0] * 26
 
        # Counting occurrence of each
        # character of current string
        for j in range(len(s[i])):
            a[ord(s[i][j]) - ord('a')] += 1
 
        # Convert each count to parity(0 or 1)
        # on the basis of its frequency
        for j in range(26):
            a[j] = a[j] % 2
 
        # Adding to answer
        ans += mp[tuple(a)]
 
        # Frequency of single character
        # can be possibly changed,
        # so change its parity
        for j in range(26):
            changedCount = a[:]
            if (a[j] == 0):
                changedCount[j] = 1
            else:
                changedCount[j] = 0
            ans += mp[tuple(changedCount)]
 
        mp[tuple(a)] += 1
 
    return ans
 
# Driver code
if __name__ == '__main__':
     
    N = 6
    A = [ "aab", "abcac", "dffe",
        "ed", "aa", "aade" ]
 
    print(getCount(N, A))
 
# This code is contributed by Shivam Singh


输出:
6

时间复杂度: O(N*(L+log(N))),其中L是字符串的最大长度
辅助空间: O(N)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程