📌  相关文章
📜  找到每个子串的字符串正好有 K 个不同的字符

📅  最后修改于: 2021-09-04 08:29:28             🧑  作者: Mango

给定两个整数NK 。任务是找到长度为 N字符串,使得每个长度大于等于K 的子字符串都恰好有K 个不同的字符。
例子:

Input: N=10, K=3
Output : ABCABCABCA
Explanation:
The output string has 3 distinct characters.

Input : N=20, K=7
Output : ABCDEFGABCDEFGABCDEF
Explanation:
The output string has 7 distinct characters.

方法:
为了解决上面提到的问题,主要思想是打印不同的元素直到长度K ,然后重复相同的元素直到N
下面是上述方法的实现:

C++
// C++ Program to Find the
// String having each substring
// with exactly K distinct characters
#include 
using namespace std;
 
// Function to find the
// required output string
void findString(int N, int K)
{
    // Each element at index
    // i is modulus of K
    for (int i = 0; i < N; i++) {
 
        cout << char('A' + i % K);
    }
}
 
// Driver code
int main()
{
    // initialise integers N and K
    int N = 10;
    int K = 3;
 
    findString(N, K);
 
    return 0;
}


Java
// Java program to find the
// string having each substring
// with exactly K distinct characters
import java.io.*;
 
class GFG {
 
// Function to find the
// required output string
static void findString(int N, int K)
{
     
    // Each element at index
    // i is modulus of K
    for (int i = 0; i < N; i++)
    {
        System.out.print((char)('A' + i % K));
    }
}
 
// Driver code
public static void main(String[] args)
{
    // Initialise integers N and K
    int N = 10;
    int K = 3;
    findString(N, K);
}
}
 
// This code is contributed by shivanisinghss2110


Python3
# Python3 Program to Find the
# String having each substring
# with exactly K distinct characters
 
# Function to find the
# required output string
def findString(N, K) :
    # Each element at index
    # i is modulus of K
    for i in range(N) :
 
        print(chr(ord('A') + i % K),end="");
 
# Driver code
if __name__ == "__main__" :
    # initialise integers N and K
    N = 10;
    K = 3;
 
    findString(N, K);
     
# This code is contributed by AnkitRai01


C#
// C# program to find the
// string having each substring
// with exactly K distinct characters
using System;
 
class GFG {
 
// Function to find the
// required output string
static void findString(int N, int K)
{
     
    // Each element at index
    // i is modulus of K
    for(int i = 0; i < N; i++)
    {
       Console.Write((char)('A' + i % K));
    }
}
 
// Driver code
public static void Main(String[] args)
{
     
    // Initialise integers N and K
    int N = 10;
    int K = 3;
 
    findString(N, K);
}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
ABCABCABCA

时间复杂度: O(N)

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