寻找独一无二的糖葫芦串的题解| 豆包MarsCode AI刷题

124 阅读3分钟

问题描述

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

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

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

解题思路

  1. 理解问题

    • 题目目的为找到甜度最大的独一无二的糖葫芦,由题意可知糖葫芦独一无二当且仅当它与其他糖葫芦都不同,且翻转后的字符串也不能与其他糖葫芦相同。
  2. 数据结构选择

    • 可以使用 Map<String, Integer> 来存储每个字符串及其对应的甜度。
    • 可以使用 Set<String> 来存储独一无二的字符串。

解题步骤

  1. 计算甜度

    • 首先需要计算每个字符串的甜度。甜度可以通过字符与 'a' 的差值来计算。
  2. 处理字符串的唯一性

    • 其次通过比较字符串及其翻转后的字符串来判断每个字符串是否是独一无二的。
  3. 存储和比较

    • 然后使用合适的数据结构来存储字符串及其甜度,并进行比较。
  4. 返回结果

    • 如果没有独一无二的糖葫芦,返回 0;否则返回甜度最大的独一无二的糖葫芦的甜度。

代码实现

以下为上述思路的Java代码实现:

import java.util.*;
public class Main {
    public static int solution(int n, int m, String[] strings) {
        // write code here
        Map<String, Integer> sweetnessMap = new HashMap<>();
        
        // 用于存储独一无二的字符串
        Set<String> uniqueStrings = new HashSet<>();
        
        // 遍历每个字符串
        for (String str : strings) {
            // 计算字符串的甜度
            int sweetness = calculateSweetness(str);
            
            // 生成字符串及其翻转后的字符串
            String reversedStr = new StringBuilder(str).reverse().toString();
            
            // 判断是否独一无二
            if (!sweetnessMap.containsKey(str) && !sweetnessMap.containsKey(reversedStr)) {
                sweetnessMap.put(str, sweetness);
                uniqueStrings.add(str);
            } else {
                // 如果已经存在,则移除
                uniqueStrings.remove(str);
                uniqueStrings.remove(reversedStr);
            }
        }
        
        // 找到甜度最大的独一无二的字符串
        int maxSweetness = 0;
        for (String uniqueStr : uniqueStrings) {
            maxSweetness = Math.max(maxSweetness, sweetnessMap.get(uniqueStr));
        }
        
        return maxSweetness;
    }
    // 计算字符串的甜度
    private static int calculateSweetness(String str) {
        int sweetness = 0;
        for (char c : str.toCharArray()) {
            sweetness += c - 'a';
        }
        return sweetness;
    }

    public static void main(String[] args) {
        System.out.println(solution(3, 3, new String[]{"ccz", "cba", "zcc"}) == 3);
        System.out.println(solution(2, 3, new String[]{"abc", "cba"}) == 0);
        System.out.println(solution(5, 2, new String[]{"aa", "bb", "ab", "ba", "cc"}) == 4);
    }
}

详细步骤

  1. 计算甜度

    • 遍历字符串中的每个字符,计算其与 'a' 的差值,累加得到字符串的甜度。
  2. 生成翻转字符串

    • 使用 StringBuilder 的 reverse() 方法生成字符串的翻转字符串。
  3. 检查唯一性

    • 使用 Map 的 containsKey 方法检查字符串及其翻转字符串是否已经存在。
    • 如果都不存在,则将字符串及其甜度添加到 Map 中,并将字符串添加到 Set 中。
    • 如果存在,则从 Set 中移除该字符串及其翻转字符串。
  4. 找到最大甜度

    • 遍历 Set 中的字符串,使用 Map 获取每个字符串的甜度,并找到最大值。

总结

在解题的过程中我学习到了生成翻转字符串的字符串处理方法和如何进行唯一性判断,以及对如何遍历输入字符串数组并对每个字符串进行处理更加熟练。