给定长度为N的字符串S,要构造一个长度为N的字符串T。期初,T是一个空串,随后反复进行下列任意操作:
从S的头部删除一个字符,加到T的尾部;从S的尾部删除一个字符,加到T的尾部。
目标是要构造字典序尽可能小的字符串T。
当N=6,输入S="ACDBCB"时,输出T="ABCBCD"。
将S反转后的字符串定为S',比较S和S'的字典序,如果S较小则从S开头取字符加到T的末尾,反之从S末尾取字符加到T的末尾。
#include <stdio.h>
#include <tchar.h>
#include <queue>
#include "iostream"
using namespace std;
const int N = 6;
char S[N] = "ACDBCD";
char* solve(char S[])
{
int start = 0, end = N - 1;
bool isLeft = false;
char T[N];
while(start <= end) {
for(int i = 0; start + i < end; i++)
{
if(S[start + i] < S[end - i])
{
isLeft = true;
break;
}
else if(S[start + i] > S[end -i])
{
isLeft = false;
break;
}
else
continue;
}
if(isLeft)
{
T[N-(end - start + 1)] = S[start++];
}
else
{
T[N-(end - start + 1)] = S[end--];
}
}
return T;
}
int main() {
char *result = solve(S);
for(int i=0; i<N; i++)
{
putchar(result[i]);
}
return 0;
}
From 计蒜客