给定两个正整数N,M 。任务是在大小为M的字母集下找到长度为N的字符串数,以使回文大小不大于1。
例子:
Input : N = 2, M = 3
Output : 6
In this case, set of alphabet are 3, say {A, B, C}
All possible string of length 2, using 3 letters are:
{AA, AB, AC, BA, BB, BC, CA, CB, CC}
Out of these {AA, BB, CC} contain palindromic substring,
so our answer will be
8 - 2 = 6.
Input : N = 2, M = 2
Output : 2
Out of {AA, BB, AB, BA}, only {AB, BA} contain
non-palindromic substrings.
首先,观察,一个字符串不包含任何回文子,如果该字符串不具有长度2和3的任何回文串,因为更长的长度的所有的回文字符串包含的2或长度中的至少一个回文子串3,基本上在中心。
因此,以下是正确的:
- 有M种方法选择字符串的第一个符号。
- 然后,有(M – 1)种方法选择字符串的第二个符号。基本上,它不应该等于第一个。
- 然后,有(M – 2)种方法来选择下一个符号。基本上,它不应与之前的符号(不相等)重合。
知道了这一点,我们可以通过以下方式评估答案:
- 如果N = 1,则答案将是M。
- 如果N = 2,则答案为M *(M – 1)。
- 如果N> = 3,则M *(M – 1)*(M – 2) N-2 。
下面是上述想法的实现:
C++
// CPP program to count number of strings of
// size m such that no substring is palindrome.
#include
using namespace std;
// Return the count of strings with
// no palindromic substring.
int numofstring(int n, int m)
{
if (n == 1)
return m;
if (n == 2)
return m * (m - 1);
return m * (m - 1) * pow(m - 2, n - 2);
}
// Driven Program
int main()
{
int n = 2, m = 3;
cout << numofstring(n, m) << endl;
return 0;
}
Java
// Java program to count number of strings of
// size m such that no substring is palindrome.
import java.io.*;
class GFG {
// Return the count of strings with
// no palindromic substring.
static int numofstring(int n, int m)
{
if (n == 1)
return m;
if (n == 2)
return m * (m - 1);
return m * (m - 1) * (int)Math.pow(m - 2, n - 2);
}
// Driven Program
public static void main (String[] args)
{
int n = 2, m = 3;
System.out.println(numofstring(n, m));
}
}
// This code is contributed by ajit.
Python3
# Python3 program to count number of strings of
# size m such that no substring is palindrome
# Return the count of strings with
# no palindromic substring.
def numofstring(n, m):
if n == 1:
return m
if n == 2:
return m * (m - 1)
return m * (m - 1) * pow(m - 2, n - 2)
# Driven Program
n = 2
m = 3
print (numofstring(n, m))
# This code is contributed
# by Shreyanshi Arun.
C#
// C# program to count number of strings of
// size m such that no substring is palindrome.
using System;
class GFG {
// Return the count of strings with
// no palindromic substring.
static int numofstring(int n, int m)
{
if (n == 1)
return m;
if (n == 2)
return m * (m - 1);
return m * (m - 1) * (int)Math.Pow(m - 2,
n - 2);
}
// Driver Code
public static void Main ()
{
int n = 2, m = 3;
Console.Write(numofstring(n, m));
}
}
// This code is contributed by Nitin Mittal.
PHP
Javascript
输出
6