华为OD上机考试真题(Java)——字符串分割

发布于:2025-02-10 ⋅ 阅读:(75) ⋅ 点赞:(0)

题目

给定一个字符串,只包含小写字母,字符串长度是 5-30。
求:是否存在两个节点,使得字符串被这两个节点分成三个部分,每个部分的 ASCII 码的值之和都相等。如果存在输出两个节点下标,以逗号隔开。下标从 0 开始,如果不存在,则输出 0,0。如果存在答案,则是唯一解。

示例一:

输入

abcbbbcab

输出

2,5

说明:以位置2和5作为分割点,将字符串分割为ac,bb,ca三个子串,每一个的子串权重都为196,输出为:2,5

示例二:

输入

abcabc

输出

0,0

说明:找不到符合条件的分割点,输出为0,0

示例三:

输入

abzba

输出

0,0

先看结果
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

通过以下步骤来实现:

  1. 读取输入
    • 读取一个字符串。
  2. 计算每个字符的ASCII值之和
    • 计算整个字符串的ASCII值之和。
  3. 寻找分割点
    • 遍历所有可能的分割点,检查是否满足条件。
  4. 输出结果
    • 如果找到符合条件的分割点,输出分割点的下标;否则输出 0,0

下面是一个具体的Java代码实现:

import java.util.Scanner;

public class StringSplitter {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Read the input string
        String input = scanner.nextLine();
        
        // Calculate the total ASCII sum of the string
        int totalSum = 0;
        for (char c : input.toCharArray()) {
            totalSum += c;
        }
        
        // Check if the total sum is divisible by 3
        if (totalSum % 3 != 0) {
            System.out.println("0,0");
            return;
        }
        
        int targetSum = totalSum / 3;
        int currentSum = 0;
        int firstIndex = -1;
        int secondIndex = -1;
        
        // Iterate through the string to find the split points
        for (int i = 0; i < input.length() - 1; i++) {
            currentSum += input.charAt(i);
            
            // Check if we have found the first split point
            if (currentSum == targetSum && firstIndex == -1) {
                firstIndex = i;
            } else if (currentSum == 2 * targetSum && secondIndex == -1) {
                secondIndex = i;
            }
        }
        
        // Check if both split points are found
        if (firstIndex != -1 && secondIndex != -1) {
            System.out.println(firstIndex + "," + secondIndex);
        } else {
            System.out.println("0,0");
        }
    }
}

解释

  1. 读取输入

    • 使用 Scanner 类从标准输入读取字符串。
  2. 计算每个字符的ASCII值之和

    • 遍历字符串中的每个字符,累加其ASCII值。
  3. 寻找分割点

    • 计算目标和 targetSum,即总和除以3。
    • 遍历字符串,累加当前和 currentSum
    • currentSum 等于 targetSum 时,记录第一个分割点。
    • currentSum 等于 2 * targetSum 时,记录第二个分割点。
  4. 输出结果

    • 如果找到了两个分割点,输出它们的下标(从0开始)。
    • 否则,输出 0,0

示例运行

假设输入为:

abcbbbacb

程序将输出:

2,5

在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到