zoukankan      html  css  js  c++  java
  • 寻找最小字典序字符串(水题打卡)

    题目:

    长度为 n 的环状串有 n 种表示法,分别从某位置开始顺时针得到。在这些表示法中,字典序最小的称为“最小表示”,你的任务是输出该环状串的最小表示。(n <= 100)

    解题思路:

    枚举n个位置(起始位置),并记录当前字典序最小的位置,总的时间复杂度O(n * n),由于n较小,没问题。

    代码:

     1 #include<stdio.h>
     2 #include<stdbool.h>
     3 #include<iostream>
     4 using namespace std;
     5 const int maxn = 1000 * 2 + 10;
     6 char str[maxn];
     7 
     8 //若环状串str的表示法p比表示法q小,返回1
     9 //若环状串str的表示法p比表示法q大,返回-1
    10 //相等,返回0
    11 int cmp(char * str,int p,int q,int len)
    12 {
    13     int T = len;
    14     while (T--)
    15     {
    16         if (str[p] == str[q])
    17         {
    18             p++;
    19             q++;
    20         }
    21         else if (str[p] > str[q])
    22             return -1;
    23         else
    24             return  1;
    25     }
    26     return 0;
    27 }
    28 int main()
    29 {
    30     int n;
    31     scanf("%d", &n);
    32     while (n--)
    33     {
    34         int res = 0;
    35         scanf("%s", str);
    36         int len = strlen(str);
    37         
    38         //将字符串扩展2倍,操作起来十分方便
    39         for (int i = 0; i < 2 * len; i++)
    40             str[i] = str[i % len];
    41 
    42         //寻找使字符串字典序最小的位置
    43         for (int i = 0; i < len; i++)
    44             if (cmp(str, i, res, len) > 0)  res = i;
    45 
    46         //输出结果,往后输出n位就可以了
    47         for (int i = 0; i < len; i++)
    48         {
    49             printf("%c", str[res + i]);
    50             if (i == len - 1)
    51                 printf("
    ");
    52         }
    53     }
    54     return 0;
    55 }
  • 相关阅读:
    在Objective-C声明Block的几种方式
    属性初始化
    OC协议
    堆排序的OC实现
    iOS 应用性能测试的相关方法、工具及技巧
    墙裂推荐 iOS 资源大全
    剖析@weakify 和 @strongify
    iOS开发大神必备的Xcode插件
    聊聊 KVC 和 KVO 的高阶应用
    TableView的优化
  • 原文地址:https://www.cnblogs.com/lfri/p/9329945.html
Copyright © 2011-2022 走看看