📜  构造一个长度为L的字符串,以使每个长度为X的子字符串都具有正好Y个不同的字母

📅  最后修改于: 2021-06-25 21:07:51             🧑  作者: Mango

给定字符串l长度,子字符串x长度以及长度为x的子字符串必须具有的不同字符数为y,任务是找到一个长度为l的字符串,其中每个长度x的子字符串都具有y字符鲜明。
例子:

方法:
为了解决上述问题,我们遵循以下步骤:

  • 将变量p初始化为97,该变量标记小写字母“ a”的ASCII值。
  • 不断增加p的值,直到y个字符。
  • 然后从第一个字符重复该字符,直到其长度等于给定字符串的长度,然后返回最后一个字符串。

下面是上述方法的实现:

C++
// C++ implementation to
// construct a string of length L
// such that each substring of length
// X has exactly Y distinct letters.
#include 
using namespace std;
 
void String(int l, int x, int y)
{
    // Initialize p equal to the ASCII value of a
    int p = 97;
     
    // Iterate till the length of the string
    for(int j = 0; j < l ; j++)
    {
        char ans = (char)(p + (j % y));
        cout << ans;
    }
}
     
// Driver code
int main ()
{
    int l = 6;
    int x = 5;
    int y = 3;
    String(l, x, y) ;
    return 0;
}
 
// This code is contributed by AnkitRai01


Java
// Java implementation to
// construct a string of length L
// such that each substring of length
// X has exactly Y distinct letters.
 
public class GFG {
         
    static void string(int l, int x, int y){
         
        // Initialize p equal to the ASCII value of a
        int p = 97;
     
        // Iterate till the length of the string
        for(int j = 0; j < l ; j++){
             
            char ans = (char)(p + (j % y));
            System.out.print(ans);
        }
             
    }
     
    // Driver code
    public static void main (String[] args) {
    int l = 6;
    int x = 5;
    int y = 3;
    string(l, x, y) ;
        }
}
// This code is contributed by AnkitRai01


Python3
# Python implementation to
# construct a string of length L
# such that each substring of length
# X has exactly Y distinct letters.
 
def String(l, x, y):
    # Initialize p equal to the ASCII value of a
    p = 97
 
    # Iterate till the length of the string
    for j in range(l):
         
        ans = chr(p + j % y)
        print(ans, end ="")
         
 
# Driver code
l = 6
x = 5
y = 3
String(l, x, y)


C#
// C# implementation to
// construct a string of length L
// such that each substring of length
// X has exactly Y distinct letters.
using System;
 
class GFG {
    static void String(int l, int x, int y)
    {
        // Initialize p equal to the ASCII value of a
        int p = 97;
     
        // Iterate till the length of the string
        for(int j = 0; j < l; j++)
        {
            char ans = (char)(p + (j % y));
            Console.Write(ans);
        }
    }
     
    // Driver code
    public static void Main(string[] args)
    {
        int l = 6;
        int x = 5;
        int y = 3;
        String(l, x, y);
    }
}
 
// This code is contributed by AnkitRai01


Javascript


输出:
abcabc

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。