bluecode-字典序最小回文构造问题

19 阅读1分钟

问题描述

小R手中有一个由小写英文字母组成的字符串。她希望将这个字符串转换为回文字符串,并且要求字典序尽可能小。在这个过程中,小R最多可以更改字符串中的两个字符。每个字符可以被更改为任意的小写字母。现在你的任务是帮助小R构造出在满足条件的前提下字典序最小的回文字符串,测试数据保证答案存在。

例如:对于字符串 acca,通过更改两个字符,可以得到回文字符串 aaaa,这是字典序最小的解。


测试样例

样例1:

输入:s = "acca"
输出:'aaaa'

样例2:

输入:s = "racecar"
输出:'aacecaa'

样例3:

输入:s = "fecdef"
输出:'feaaef'

#include <iostream>
#include <string>
#include <vector>


std::string solution(const std::string &s) {
  std::string result = s;
  int changes = 0;
  int left = 0;
  int right = result.size() - 1;

  // First pass: make the string a palindrome
  while (left < right) {
    if (result[left] != result[right]) {
      if (result[left] != 'a' && result[right] != 'a' && changes + 2 <= 2) {
        result[left] = 'a';
        result[right] = 'a';
        changes += 2;
      } else {
        if (result[left] > result[right]) {
          result[left] = result[right];
        } else {
          result[right] = result[left];
        }
        changes += 1;
      }
    }
    left++;
    right--;
  }

  // Second pass: try to make the string as small as possible with remaining
  // changes
  left = 0;
  right = result.size() - 1;
  while (left <= right && changes < 2) {
    if (left == right) {
      if (result[left] != 'a') {
        result[left] = 'a';
        changes += 1;
      }
    } else {
      if (result[left] != 'a') {
        if (changes + 2 <= 2) {
          result[left] = 'a';
          result[right] = 'a';
          changes += 2;
        }
      }
    }
    left++;
    right--;
  }

  return result;
}

int main() {
  std::cout << (solution("acca") == "aaaa") << std::endl;
  std::cout << (solution("racecar") == "aacecaa") << std::endl;
  std::cout << (solution("fecdef") == "feaaef") << std::endl;
  return 0;
}