Untitled

 avatar
unknown
c_cpp
11 days ago
1.1 kB
4
Indexable
#include <bits/stdc++.h>
using namespace std;

string getEncodedName(string letters) {
    int n = letters.size();
    vector<int> freq(26, 0);
    
    // Count frequency of each character
    for (char c : letters) {
        freq[c - 'a']++;
    }

    // Count how many characters have odd frequencies
    int oddCount = 0;
    for (int i = 0; i < 26; i++) {
        if (freq[i] % 2 == 1) oddCount++;
    }

    // If more than one character has an odd frequency, return "NO SOLUTION"
    if (oddCount > 1) return "NO SOLUTION";

    // Form the smallest lexicographic half of the palindrome
    string half = "", mid = "";
    for (int i = 0; i < 26; i++) {
        if (freq[i] % 2 == 1) {
            mid += (char)(i + 'a'); // At most one character can be odd
        }
        half += string(freq[i] / 2, (char)(i + 'a'));
    }

    // Construct the lexicographically smallest palindrome
    string result = half + mid + string(half.rbegin(), half.rend());
    return result;
}

int main() {
    string letters;
    cin >> letters;
    cout << getEncodedName(letters) << endl;
    return 0;
}
Leave a Comment