📌  相关文章
📜  计算给定字符串的子字符串,其字谜是回文

📅  最后修改于: 2021-09-07 02:20:09             🧑  作者: Mango

给定一个仅包含小写字母的长度为N的字符串S ,任务是打印给定字符串的回文字串的子串计数。

例子:

朴素的方法:这个想法是生成给定字符串的所有子串,对于每个子串,检查它的字谜是否是回文。继续增加发现上述条件为真的子串的计数。最后,打印所有此类子字符串的计数。
时间复杂度: O(N 3 )
辅助空间: O(N)

位掩码方法:这个想法是生成26 位数字的掩码,因为有26 个字符。另外,请注意,如果某个字符串的字谜是回文,那么除了最多一个字符外,其字符的频率必须是偶数。
请按照以下步骤解决问题:

  • 遍历字符串并在每个索引处初始化一个变量X = 0
  • 从每个i索引,遍历字符串在一定范围的指数的[I,N – 1],并且对于每个字符S [j],X的计算按位XOR和2(S [j]的- ‘A’),其中0位代表是否频率是奇数,1表示如果b的频率为奇数,等等。
  • 然后,检查X & (X – 1)是否等于0 。如果发现为真,则将计数增加1
  • 完成上述步骤后,打印获得的计数。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to print count of substrings
// whose anagrams are palindromic
void countSubstring(string s)
{
    // Stores the answer
    int res = 0;
 
    // Iterate over the string
    for (int i = 0;
         i < s.length(); i++) {
 
        int x = 0;
 
        for (int j = i;
             j < s.length(); j++) {
 
            // Set the current character
            int temp = 1 << s[j] - 'a';
 
            // Parity update
            x ^= temp;
            if ((x & (x - 1)) == 0)
                res++;
        }
    }
 
    // Print the final count
    cout << res;
}
 
// Driver Code
int main()
{
    string str = "aaa";
 
    // Function Call
    countSubstring(str);
 
    return 0;
}


Java
// Java program for
// the above approach
class GFG{
 
// Function to print count of subStrings
// whose anagrams are palindromic
static void countSubString(String s)
{
  // Stores the answer
  int res = 0;
 
  // Iterate over the String
  for (int i = 0; i < s.length(); i++)
  {
    int x = 0;
    for (int j = i; j < s.length(); j++)
    {
      // Set the current character
      int temp = 1 << s.charAt(j) - 'a';
 
      // Parity update
      x ^= temp;
      if ((x & (x - 1)) == 0)
        res++;
    }
  }
 
  // Print the final count
  System.out.print(res);
}
 
// Driver Code
public static void main(String[] args)
{
  String str = "aaa";
 
  // Function Call
  countSubString(str);
}
}
 
// This code is contributed by shikhasingrajput


Python3
# Python3 program for
# the above approach
 
# Function to prcount of subStrings
# whose anagrams are palindromic
def countSubString(s):
   
    # Stores the answer
    res = 0;
 
    # Iterate over the String
    for i in range(len(s)):
        x = 0;
        for j in range(i, len(s)):
           
            # Set the current character
            temp = 1 << ord(s[j]) - ord('a');
 
            # Parity update
            x ^= temp;
            if ((x & (x - 1)) == 0):
                res += 1;
 
    # Print final count
    print(res);
 
# Driver Code
if __name__ == '__main__':
    str = "aaa";
 
    # Function Call
    countSubString(str);
 
# This code is contributed by 29AjayKumar


C#
// C# program for
// the above approach
using System;
class GFG{
 
// Function to print count of subStrings
// whose anagrams are palindromic
static void countSubString(String s)
{
  // Stores the answer
  int res = 0;
 
  // Iterate over the String
  for (int i = 0; i < s.Length; i++)
  {
    int x = 0;
 
    for (int j = i; j < s.Length; j++)
    {
      // Set the current character
      int temp = 1 << s[j] - 'a';
 
      // Parity update
      x ^= temp;
      if ((x & (x - 1)) == 0)
        res++;
    }
  }
 
  // Print the readonly count
  Console.Write(res);
}
 
// Driver Code
public static void Main(String[] args)
{
  String str = "aaa";
 
  // Function Call
  countSubString(str);
}
}
 
// This code is contributed by shikhasingrajput


Javascript


C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to get the count of substrings
// whose anagrams are palindromic
void countSubstring(string s)
{
    // Store the answer
    int answer = 0;
 
    // Map to store the freq of masks
    unordered_map m;
 
    // Set frequency for mask
    // 00...00 to 1
    m[0] = 1;
 
    // Store mask in x from 0 to i
    int x = 0;
    for (int j = 0; j < s.length(); j++) {
        x ^= 1 << (s[j] - 'a');
 
        // Update answer
        answer += m[x];
        for (int i = 0; i < 26; ++i) {
            answer += m[x ^ (1 << i)];
        }
 
        // Update frequency
        m[x] += 1;
    }
 
    // Print the answer
    cout << answer;
}
 
// Driver Code
int main()
{
    string str = "abab";
 
    // Function Call
    countSubstring(str);
    return 0;
}


Java
// Java program for
// the above approach
import java.util.*;
class GFG {
 
// Function to get the count of subStrings
// whose anagrams are palindromic
static void countSubString(String s)
{
  // Store the answer
  int answer = 0;
 
  // Map to store the freq of masks
  HashMap m = new HashMap();
   
  // Set frequency for mask
  // 00...00 to 1
  m.put(0, 1);
 
  // Store mask in x from 0 to i
  int x = 0;
  for (int j = 0; j < s.length(); j++)
  {
    x ^= 1 << (s.charAt(j) - 'a');
 
    // Update answer
    answer += m.containsKey(x) ? m.get(x) : 0;
    for (int i = 0; i < 26; ++i)
    {
      answer += m.containsKey(x ^ (1 << i)) ?
                m.get(x ^ (1 << i)) : 0;
    }
 
    // Update frequency
    if (m.containsKey(x))
      m.put(x, m.get(x) + 1);
    else
      m.put(x, 1);
  }
 
  // Print the answer
  System.out.print(answer);
}
 
// Driver Code
public static void main(String[] args)
{
  String str = "abab";
 
  // Function Call
  countSubString(str);
}
}
 
// This code is contributed by shikhasingrajput


Python3
# Python3 program for the above approach
from collections import defaultdict
 
# Function to get the count of substrings
# whose anagrams are palindromic
def countSubstring(s):
 
    # Store the answer
    answer = 0
 
    # Map to store the freq of masks
    m = defaultdict(lambda : 0)
 
    # Set frequency for mask
    # 00...00 to 1
    m[0] = 1
 
    # Store mask in x from 0 to i
    x = 0
     
    for j in range(len(s)):
        x ^= 1 << (ord(s[j]) - ord('a'))
 
        # Update answer
        answer += m[x]
        for i in range(26):
            answer += m[x ^ (1 << i)]
 
        # Update frequency
        m[x] += 1
 
    # Print the answer
    print(answer)
 
# Driver Code
str = "abab"
 
# Function call
countSubstring(str)
 
# This code is contributed by Shivam Singh


C#
// C# program for
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to get the count of
// subStrings whose anagrams
// are palindromic
static void countSubString(String s)
{
  // Store the answer
  int answer = 0;
 
  // Map to store the freq of masks
  Dictionary m = new Dictionary();
   
  // Set frequency for mask
  // 00...00 to 1
  m.Add(0, 1);
 
  // Store mask in x from 0 to i
  int x = 0;
  for (int j = 0; j < s.Length; j++)
  {
    x ^= 1 << (s[j] - 'a');
 
    // Update answer
    answer += m.ContainsKey(x) ? m[x] : 0;
    for (int i = 0; i < 26; ++i)
    {
      answer += m.ContainsKey(x ^ (1 << i)) ?
                m[x ^ (1 << i)] : 0;
    }
 
    // Update frequency
    if (m.ContainsKey(x))
      m[x] = m[x] + 1;
    else
      m.Add(x, 1);
  }
 
  // Print the answer
  Console.Write(answer);
}
 
// Driver Code
public static void Main(String[] args)
{
  String str = "abab";
 
  // Function Call
  countSubString(str);
}
}
 
// This code is contributed by shikhasingrajput


Javascript


输出
6

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

有效的方法:为了优化上述位掩码技术,想法是使用映射。请按照以下步骤解决问题:

  1. 初始化地图以存储掩码的频率。初始化一个变量X = 0
  2. 遍历字符串,对于每个i索引,计算X2 (S[j] – ‘a’) 的按位异或,并通过添加 Map 中X的当前值的频率来更新答案,因为如果任何来自0 的子字符串to jX 的掩码相同,它是从0i 的子串的掩码,然后子串S[j + 1, i]将具有偶数频率,其中j < i
  3. 还要添加掩码X xor 2 k的频率,其中0 ≤ k < 26 。之后,将X的频率增加1
  4. 对给定字符串的每个索引重复上述步骤。
  5. 遍历给定的字符串,打印所需的答案

下面是上述方法的实现:

C++

// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to get the count of substrings
// whose anagrams are palindromic
void countSubstring(string s)
{
    // Store the answer
    int answer = 0;
 
    // Map to store the freq of masks
    unordered_map m;
 
    // Set frequency for mask
    // 00...00 to 1
    m[0] = 1;
 
    // Store mask in x from 0 to i
    int x = 0;
    for (int j = 0; j < s.length(); j++) {
        x ^= 1 << (s[j] - 'a');
 
        // Update answer
        answer += m[x];
        for (int i = 0; i < 26; ++i) {
            answer += m[x ^ (1 << i)];
        }
 
        // Update frequency
        m[x] += 1;
    }
 
    // Print the answer
    cout << answer;
}
 
// Driver Code
int main()
{
    string str = "abab";
 
    // Function Call
    countSubstring(str);
    return 0;
}

Java

// Java program for
// the above approach
import java.util.*;
class GFG {
 
// Function to get the count of subStrings
// whose anagrams are palindromic
static void countSubString(String s)
{
  // Store the answer
  int answer = 0;
 
  // Map to store the freq of masks
  HashMap m = new HashMap();
   
  // Set frequency for mask
  // 00...00 to 1
  m.put(0, 1);
 
  // Store mask in x from 0 to i
  int x = 0;
  for (int j = 0; j < s.length(); j++)
  {
    x ^= 1 << (s.charAt(j) - 'a');
 
    // Update answer
    answer += m.containsKey(x) ? m.get(x) : 0;
    for (int i = 0; i < 26; ++i)
    {
      answer += m.containsKey(x ^ (1 << i)) ?
                m.get(x ^ (1 << i)) : 0;
    }
 
    // Update frequency
    if (m.containsKey(x))
      m.put(x, m.get(x) + 1);
    else
      m.put(x, 1);
  }
 
  // Print the answer
  System.out.print(answer);
}
 
// Driver Code
public static void main(String[] args)
{
  String str = "abab";
 
  // Function Call
  countSubString(str);
}
}
 
// This code is contributed by shikhasingrajput

蟒蛇3

# Python3 program for the above approach
from collections import defaultdict
 
# Function to get the count of substrings
# whose anagrams are palindromic
def countSubstring(s):
 
    # Store the answer
    answer = 0
 
    # Map to store the freq of masks
    m = defaultdict(lambda : 0)
 
    # Set frequency for mask
    # 00...00 to 1
    m[0] = 1
 
    # Store mask in x from 0 to i
    x = 0
     
    for j in range(len(s)):
        x ^= 1 << (ord(s[j]) - ord('a'))
 
        # Update answer
        answer += m[x]
        for i in range(26):
            answer += m[x ^ (1 << i)]
 
        # Update frequency
        m[x] += 1
 
    # Print the answer
    print(answer)
 
# Driver Code
str = "abab"
 
# Function call
countSubstring(str)
 
# This code is contributed by Shivam Singh

C#

// C# program for
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to get the count of
// subStrings whose anagrams
// are palindromic
static void countSubString(String s)
{
  // Store the answer
  int answer = 0;
 
  // Map to store the freq of masks
  Dictionary m = new Dictionary();
   
  // Set frequency for mask
  // 00...00 to 1
  m.Add(0, 1);
 
  // Store mask in x from 0 to i
  int x = 0;
  for (int j = 0; j < s.Length; j++)
  {
    x ^= 1 << (s[j] - 'a');
 
    // Update answer
    answer += m.ContainsKey(x) ? m[x] : 0;
    for (int i = 0; i < 26; ++i)
    {
      answer += m.ContainsKey(x ^ (1 << i)) ?
                m[x ^ (1 << i)] : 0;
    }
 
    // Update frequency
    if (m.ContainsKey(x))
      m[x] = m[x] + 1;
    else
      m.Add(x, 1);
  }
 
  // Print the answer
  Console.Write(answer);
}
 
// Driver Code
public static void Main(String[] args)
{
  String str = "abab";
 
  // Function Call
  countSubString(str);
}
}
 
// This code is contributed by shikhasingrajput

Javascript


输出
7

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

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