虽然我真的只需要一个旋转算法,但字符串似乎是最容易做到的事情,虽然因为这不是任何特定语言所以它确实无关紧要。如何改变
ab
c
到
b
ac
答案 0 :(得分:0)
有几种解决方案。 I guess this can give you an idea(C中的数组旋转解决方案)
这个使用字符
#include <stdio.h>
#include <string.h>
/* Left rotation of a string is to move some leading characters to its end, for example, if the input string is “abcdefg” and a number 2, two characters are rotated and the result
is “cdefgab”. */
void solution1(char *s, int n, int rotate) {
char new_s[n * 2 + 1];
strcpy(new_s, s);
strcat(new_s, s);
for (int i = 0; i < n; i++) /* extract s from "abcdeabcde" */
s[i] = new_s[i + rotate];
printf("%s\n", s);
}
/* solution 2*/
void reverse(char *s, char *start, char *end) {
char temp;
while (start < end) {
temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
void solution2(char *s, int length, int rotate) {
char *first = s;
char *first_end = s + rotate - 1;
char *second = s + rotate;
char *second_end = s + length - 1;
if(s != NULL && length > 0 && rotate > 0 && rotate < length) {
/* Reverse the n leading characters */
reverse(s, first, first_end);
/* Reverse other characters */
reverse(s, second, second_end);
/* Reverse the whole string */
reverse(s, first, second_end);
}
}
int main() {
char s[8] = "abc";
int n = (int) strlen(s);
solution1(s, n, 2);
printf("%s\n", s);
solution2(s, n, 2);
printf("%s\n", s);
return 0;
}
此输出
sh-4.3#main
cab
cab
bca
根据你想要的结果修改它应该不是那么复杂。