gpt4 book ai didi

c - 想要打印字符串的所有旋转

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:49:35 25 4
gpt4 key购买 nike

我想一次旋转一个位置并打印所有旋转输入:S = "abc"输出:abc bca 出租车

我试图连接字符串然后打印它,但问题是输入字符串的大小可能为 10^5,因此我的数组需要 10^10 的大小。但我无法声明该大小数组,所以我想知道是否有更好的方法来做到这一点

void printRotatedString(char str[]) 
{
int n = strlen(str);

// Concatenate str with itself
char temp[2*n + 1];
strcpy(temp, str);
strcat(temp, str);

// Print all substrings of size n.

for (int i = 0; i < n; i++)
{
for (int j=0; j != n; j++)
printf("%c",temp[i + j]);
printf("\n");
}
}

我希望它甚至可以用于 10^5 大小的字符串

最佳答案

即使没有串联,您也可以做到。但你为什么需要它?如果能提供实际的问题源就更好了。

void printRotatedString(char str[]) { 
int n = strlen(str);

for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%c", str[(i + j) % n]);
printf("\n");
}
}

关于c - 想要打印字符串的所有旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57175298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com