bluecode-寻找独一无二的糖葫芦串

33 阅读1分钟

问题描述

小C有nn串长度为mm的糖葫芦,每串糖葫芦可以用一个字符串表示。每个糖葫芦的甜度是所有字符甜度的总和,其中每个字符的甜度为该字符与 'a' 的差值。例如,字符 'a' 的甜度为 00,字符 'b' 的甜度为 11,依次类推,字符 'z' 的甜度为 2525。

你需要帮助小C找到甜度最大的独一无二的糖葫芦。糖葫芦独一无二当且仅当它与其他n−1n−1根糖葫芦都不同,且翻转后的字符串也不能与其他糖葫芦相同。例如,糖葫芦 "abc" 与 "cba" 视为相同的糖葫芦。

如果没有独一无二的糖葫芦,则返回0。


测试样例

样例1:

输入:n = 3, m = 3, strings = ["ccz", "cba", "zcc"]
输出:3

样例2:

输入:n = 2, m = 3, strings = ["abc", "cba"]
输出:0

样例3:

输入:n = 5, m = 2, strings = ["aa", "bb", "ab", "ba", "cc"]
输出:4

#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <algorithm>

using namespace std;

int getSweetness(const string& s) {
    int sum = 0;
    for (char ch : s) {
        sum += ch - 'a';
    }
    return sum;
}

int solution(int n, int m, vector<string>& strings) {
    // PLEASE DO NOT MODIFY THE FUNCTION SIGNATURE

    unordered_map<string, int> countMap;

    // 统计每种糖葫芦(含反转)出现次数
    for (const string& s : strings) {
        string rev = s;
        reverse(rev.begin(), rev.end());
        string norm = min(s, rev); // 正反向字典序较小的作为 key
        countMap[norm]++;
    }

    int maxSweet = 0;

    // 找出甜度最大的独一无二糖葫芦
    for (const string& s : strings) {
        string rev = s;
        reverse(rev.begin(), rev.end());
        string norm = min(s, rev);
        if (countMap[norm] == 1) {
            int sweet = getSweetness(s);
            maxSweet = max(maxSweet, sweet);
        }
    }

    return maxSweet;
}

int main() {
    vector<string> strings1 = {"ccz", "cba", "zcc"};
    cout << (solution(3, 3, strings1) == 3) << endl;

    vector<string> strings2 = {"abc", "cba"};
    cout << (solution(2, 3, strings2) == 0) << endl;

    vector<string> strings3 = {"aa", "bb", "ab", "ba", "cc"};
    cout << (solution(5, 2, strings3) == 4) << endl;

    return 0;
}