给定的偶数整数N,任务是构造一个字符串,使得不是回文该字符串的不同子串的总数等于N 2。
例子:
Input: N = 2
Output: aabb
Explanation:
All the distinct non-palindromic substrings are ab, abb, aab and aabb.
Therefore, the count of non-palindromic substrings is 4 = 2 2
Input: N = 4
Output: cccczzzz
Explanation:
All distinct non-palindromic substrings of the string are cz, czz, czzz, czzzz, ccz, cczz, cczzz, cczzzz, cccz, ccczz, ccczzz, ccczzzz, ccccz, cccczz, cccczzz, cccczzzz.
The count of non-palindromic substrings is 16.
方法:
可以观察到的是,如果一个字符串的第一个N个字符是相同的,随后从所述第一N个字符,那么不同的非回文子串的计数将N 2不同的N个相同的字符。
Proof:
N = 3
str = “aaabbb”
The string can be split into two substrings of N characters each: “aaa” and “bbb”
The first character ‘a’ from the first substring forms N distinct non-palindromic substrings “ab”, “abb”, “abbb” with the second substring.
Similarly, first two characters “aa” forms N distinct non-palindromic substrings “aab”, “aabb”, “aabbb”.
Similarly, remaining N – 2 characters of the first substring each form N distinct non-palindromic substrings as well.
Therefore, the total number of distinct non-palindromic substrings is equal to N2.
因此,为了解决该问题,打印“A”作为字符串和“b”作为字符串的下一个N个字符的前N个字符。
下面是上述方法的实现:
C++
// C++ Program to implement
// the above approach
#include
using namespace std;
// Function to construct a string
// having N*N non-palindromic substrings
void createString(int N)
{
for (int i = 0; i < N; i++) {
cout << 'a';
}
for (int i = 0; i < N; i++) {
cout << 'b';
}
}
// Driver Code
int main()
{
int N = 4;
createString(N);
return 0;
}
Java
// Java Program to implement
// the above approach
class GFG{
// Function to construct a string
// having N*N non-palindromic substrings
static void createString(int N)
{
for (int i = 0; i < N; i++)
{
System.out.print('a');
}
for (int i = 0; i < N; i++)
{
System.out.print('b');
}
}
// Driver Code
public static void main(String[] args)
{
int N = 4;
createString(N);
}
}
// This code is contributed by shivanisinghss2110
Python3
# Python3 program to implement
# the above approach
# Function to construct a string
# having N*N non-palindromic substrings
def createString(N):
for i in range(N):
print('a', end = '')
for i in range(N):
print('b', end = '')
# Driver Code
N = 4
createString(N)
# This code is contributed by Shivam Singh
C#
// C# program to implement
// the above approach
using System;
class GFG{
// Function to construct a string
// having N*N non-palindromic substrings
static void createString(int N)
{
for(int i = 0; i < N; i++)
{
Console.Write('a');
}
for(int i = 0; i < N; i++)
{
Console.Write('b');
}
}
// Driver Code
public static void Main(String[] args)
{
int N = 4;
createString(N);
}
}
// This code is contributed by Princi Singh
Javascript
aaaabbbb
时间复杂度: O(N)
辅助空间: O(1)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live