// Algorithm / 演算法:
// 1. 若長度不同直接回傳 false / different lengths → false.
// 2. 把 s 串接自己得到 s+s / concatenate s with itself.
// 3. 用 strstr 在 s+s 裡找 goal,找到即為某種旋轉 / strstr finds goal as a substring iff goal is a rotation of s.

#include <stdbool.h>   // 提供 bool / true / false 型別 / provides the bool type
#include <string.h>    // 提供 strlen / strcpy / strcat / strstr / for string utilities
#include <stdlib.h>    // 提供 malloc / free / for dynamic memory

bool rotateString(char* s, char* goal) {
    size_t n = strlen(s);              // n = s 的長度 / length of s
    size_t m = strlen(goal);           // m = goal 的長度 / length of goal

    if (n != m) return false;          // 長度不同必不可能 / different lengths cannot be rotations

    // 配置 2n+1 個 char 的空間:2n 用來放 s+s,+1 留給結尾的 '\0' 終止符
    // Allocate 2n+1 bytes: 2n for s+s, plus 1 for the trailing null terminator '\0'.
    char* doubled = (char*)malloc(2 * n + 1);
    if (doubled == NULL) return false; // 防禦性檢查:malloc 失敗就放棄 / defensive: bail out if malloc fails

    strcpy(doubled, s);                // 先把 s 複製到 doubled / copy s into the buffer
    strcat(doubled, s);                // 再把 s 接在後面,得到 s+s / append s again, yielding s+s

    // strstr 回傳指向匹配位置的指標,沒找到回傳 NULL
    // strstr returns a pointer to the match, or NULL if not found.
    bool found = (strstr(doubled, goal) != NULL);

    free(doubled);                     // 釋放剛剛 malloc 的記憶體,避免洩漏 / free the heap allocation to avoid a leak
    return found;                      // 回傳搜尋結果 / return whether goal appears in s+s
}
