On a non-empty string, a left shift moves the first character to the end of the string, and a right shift moves the last character to the beginning of the string.
For example, a left shift on abcde
results in bcdea
, and two right shifts on abcde
result in deabc
.
You are given a non-empty SS consisting of lowercase English letters. Among the strings that can be obtained by performing zero or more left shifts and zero or more right shifts on SS, find the lexicographically smallest string and the lexicographically largest string.
- S consists of lowercase English letters.
- The length of SS is between 11 and 10001000 (inclusive)
输入:
string s
输出:
Print two lines. The first line should contain S_{\min}Smin, and the second line should contain S_{\max}Smax. Here, S_{\min}Smin and S_{\max}Smax are respectively the lexicographically smallest and largest strings obtained by performing zero or more left shifts and zero or more right shifts on SS.
样例1:
输入 | 输出 |
aaba | aaab baaa |
样例2:
输入 | 输出 |
z | z |
样例3:
输入 | 输出 |
abracadabra | aabracadabr racadabraab |
题目大意:
题目给出一个小写字母组成的字符串,可以将字符串中字母向左移(第一位移到最右),或者将字母向右移,(最后一位移到最左),然后求经过任意次操作后字典序最小和最大的字符串。
思路:
因为字符串长度为1e3,所以如果把字符串左移和右移的每种可能都枚举出来,时间复杂度1e6,再比较字典序大小
#include<bits/stdc++.h>
using namespace std;
char s[1005];
char mini[1005] = { "z" };//初始化字典序最小和最大的字符串
char maxi[1005] = { "a" };
int main()
{
cin >> s;
char temp;
if (strlen(s) == 1)//长度为1的字符串无需判断
cout << s << endl << s;
else
{
if (strcmp(s, mini) < 0)
strcpy(mini, s);
if (strcmp(s, maxi) > 0)
strcpy(maxi, s);//先比较初始的字符串的大小
for (int i = 0; i < strlen(s) - 1; i++)
{//遍历字符串中每一个字母
for (int j = 0; j < strlen(s) - 1; j++)
{//将每一个字母与他右边的字母交换位置,得到经过任意次旋转可能的字符串
temp = s[j];
s[j] = s[j + 1];
s[j + 1] = temp;
}
if (strcmp(s, mini) < 0)
strcpy(mini, s);
if (strcmp(s, maxi) > 0)
strcpy(maxi, s);
}
cout << mini << endl << maxi;
}
return 0;
}