1 条题解
-
0
JAVA题解:
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String s = reader.readLine().trim(); List<Integer> result = partitionBalloon(s); // 按要求格式输出结果 System.out.println(result); } /** * 划分气球串,使得相同颜色的气球在同一组内,且分组数量尽可能多 * * @param s 气球串 * @return 每个分组的长度列表 */ public static List<Integer> partitionBalloon(String s) { // 记录每个字符最后出现的位置 Map<Character, Integer> lastPosition = new HashMap<>(); for (int i = 0; i < s.length(); i++) { lastPosition.put(s.charAt(i), i); } List<Integer> result = new ArrayList<>(); int start = 0; // 当前分组的起始位置 int end = 0; // 当前分组的结束位置 for (int i = 0; i < s.length(); i++) { char currentChar = s.charAt(i); // 更新当前分组的最远端点 end = Math.max(end, lastPosition.get(currentChar)); // 如果当前位置达到了最远端点,说明一个分组完成了 if (i == end) { // 计算分组长度并添加到结果中 result.add(i - start + 1); // 更新下一个分组的起始位置 start = i + 1; } } return result; } }
- 1
信息
- ID
- 18
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 4
- 标签
- 递交数
- 2
- 已通过
- 1
- 上传者