美文网首页
CH3-UVA1584

CH3-UVA1584

作者: sixleaves | 来源:发表于2016-11-18 17:11 被阅读9次
    题目:

    题目很简单。给出一个字符串, 将字符串看成是一个环形的串。如果长度为n, 则这个环形串有n中读取方式。求出最小的子串。

    API:
    • strncpy(source, dest, size).其中size要加上最后一个'\0', 所以适用该方法, size = strlen(dest) + 1
    • strcmp(source, dest).其原理是source-dest的不等式, 所以<0既source < dest
    //
    // Created by sixleaves on 16/11/18.
    //
    
    #include <cstdio>
    #include <cstring>
    
    char input[126];
    char circleInput[126];
    char minCircle[126];
    void circleStringWithPos(int pos, char *initStr, char *out) {
    
        int len = strlen(initStr);
        int s = pos;
        for (int i = 0; i < len; i++) {
            out[i] = initStr[(s + i) % len];
        }
    
        out[len] = '\0';
    
    }
    
    int main() {
    
        int n;
        while (scanf("%d" , &n) == 1 && n) {
    
            for (int i = 0; i < n; i++) {
                memset(input, 0, sizeof(input));
                memset(input, 0, sizeof(circleInput));
                memset(input, 0, sizeof(minCircle));
                scanf("%s", input);
    
                int len = strlen(input);
                strncpy(minCircle, input, len + 1);
                for (int p = 0; p < len; p++) {
                    circleStringWithPos(p, input, circleInput);
                    if (strcmp(circleInput, minCircle) < 0) {
                        strncpy(minCircle, circleInput, len + 1);
                    }
                }
                printf("%s\n", minCircle);
    
            }
        }
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:CH3-UVA1584

          本文链接:https://www.haomeiwen.com/subject/hihspttx.html