题解 | #小红的字符串构造#
小红的字符串构造
https://www.nowcoder.com/practice/3e4b4dabc2e444e384c3ae62ac7dd84e
#include <stdio.h> #include <string.h> #include <stdbool.h> int main() { char s[200002]; while (scanf("%s", s) != EOF) { char t[200002]; bool c[26] = {0}; int count = 0; int cindex = -1; int lens = strlen(s); for (int i = 0; i < lens; i++) { if (c[s[i] - 'a'] == false) { c[s[i] - 'a'] = true; // printf("检查到字母%c\n", s[i]); count++; } if (count == 26) break; } if (count == 1) { printf("-1\n"); return 0; } bool used = true; for (int i = 0; i < lens; i++) { if (used == true) { for (int j = cindex + 1; j < 26; j++) { // printf("开始查找26个字母中还未被使用过的字母\n"); // printf("目前找到第%d个字母", j); if (c[j] == true) { // printf("字母%c未被使用,cindex变为%d\n", j + 'a', j); cindex = j; used = false; break; } } } if (s[i] != cindex + 'a') { t[i] = cindex + 'a'; used = true; } else { for(int j = 0; j < 26; j++) { if(c[j] == true && s[i] != j + 'a') { t[i] = j + 'a'; break; } } } } t[lens] = '\0'; printf("%s\n", t); } return 0; }