给定字符串l的长度、子字符串 x的长度以及长度为 x的子字符串必须具有的不同字符数为 y,任务是找到长度为 l 的字符串,其中每个长度为 x 的子字符串都有 y不同的字符。
例子:
Input: l = 6, x = 5, y = 3
Output: abcabc
Explanation:
If we take a substring of the first five characters then the substring will be “abcab”.
There are exactly three distinct characters (a, b, c) in the substring.
Similarly, if we take any substring from the string of length 5 then it will have
exactly 3 distinct characters.
Input: l = 3, x = 1, y = 1
Output: aaa
Explanation:
If we take the substring of length 1 then it will have exactly 1 distinct character in it.
方法:
为了解决上面提到的问题,我们按照下面给出的步骤:
- 将变量 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 Classes Live