📜  生成具有 N*N 个不同非回文子串的字符串

📅  最后修改于: 2021-09-06 05:25:23             🧑  作者: Mango

给定的偶数整数N,任务是构造一个字符串,使得不是回文该字符串的不同子串的总数等于N 2。

例子:

方法:
可以观察到的是,如果一个字符串的第一个N个字符是相同的,随后从所述第一N个字符,那么不同的非回文子串的计数将N 2不同的N个相同的字符。

因此,为了解决该问题,打印“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