思路
si,sj
分别表示剩余字符串的第一个字符和最后一个字符。
1. 如果
si<sj
,那么选择第一个字符;
2. 如果
si>sj
,那么选择最后一个字符;
3. 如果
si==sj
,需要比较下一对字符
si+1
和
sj−1
的字典序,如果还是相同就一直比较下去…直到不相等或者全部相等。不相等就选择字典序更小的一边,如果全部相等任选一边都行。
AC代码
//#define LOCAL
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
#define INF 0x3f3f3f3f
const int MAXN = 2000+5;
char s[MAXN];
bool cmp(int a, int b, int n) {
for(int i = 0; a+i <= b; i++) {
if(s[a+i] < s[b-i]) return true;
else if(s[a+i] > s[b-i]) return false;
}
return true;
}
void solve(int n) {
int l = 0, r = n-1;
int cnt = 0;
while(l <= r) {
bool left = true;
if(s[l] < s[r]) left = true;
else if(s[l] > s[r]) left = false;
else left = cmp(l, r, n);
if(left) putchar(s[l++]);
else putchar(s[r--]);
cnt++;
if(cnt == 80) {
putchar('\n');
cnt = 0;
}
}
if(cnt != 0) putchar('\n');
}
int main() {
#ifdef LOCAL
freopen("DATA/data.in", "r", stdin);
freopen("DATA/data.out", "w", stdout);
#endif
int n;
while(scanf("%d\n", &n) == 1) {
for(int i = 0; i < n; i++) scanf("%c\n", &s[i]);
solve(n);
}
return 0;
}
如有不当之处欢迎指出!