1. 实现一个函数,可以左旋字符串中的k个字符。

void rotateString(char* str, int k) {
    int length = strlen(str);
    int index;

    k %= length;
    char* newStr = (char *)malloc(sizeof(char) * length);
    for (int i = 0; i < length; i++) {
        index = ((i - k) < 0) ? (i - k + length) : (i - k);
        newStr[index] = str[i];
    }
    for (int i = 0; i < length; i++) {
        str[i] = newStr[i];
    }
}

2. 判断一个字符串是否为另外一个字符串旋转之后的字符串。

void rotateString(char* str, int k) {
    int length = strlen(str);
    int index;

    k %= length;
    char* newStr = (char *)malloc(sizeof(char) * length);
    for (int i = 0; i < length; i++) {
        index = ((i - k) < 0) ? (i - k + length) : (i - k);
        newStr[index] = str[i];
    }
    for (int i = 0; i < length; i++) {
        str[i] = newStr[i];
    }
}

int isRotated(char* a, char* b) {
    int lenA = strlen(a);
    int lenB = strlen(b);

    if (lenA != lenB)
        return 0;
    else if (lenA == 0)
        return 1;

    for (int i = 0; i < lenA; i++) {
        rotateString(a, 1);
        if (!strcmp(a, b)) {
            return 1;
        }
    }
    return 0;
}
Last modification:November 10th, 2019 at 10:20 am