You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何识别Java回文验证中不匹配的字符及位置

解决回文判断中不匹配字符的定位与计数问题

不用反转字符串后整体对比的方式,改用双指针法从字符串两端向中间遍历,逐字符对比的同时直接记录不匹配的索引位置和数量,就能实现你要的输出效果。修改后的完整代码如下:

import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;

public class Palindrome {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String stringInput = keyboard.nextLine();
        
        int left = 0;
        int right = stringInput.length() - 1;
        int mismatchCount = 0;
        List<String> mismatchPairs = new ArrayList<>();
        
        while (left < right) {
            char leftChar = stringInput.charAt(left);
            char rightChar = stringInput.charAt(right);
            
            if (leftChar != rightChar) {
                mismatchCount++;
                mismatchPairs.add(String.format("index %d and %d", left, right));
            }
            left++;
            right--;
        }
        
        if (mismatchCount == 0) {
            System.out.println(stringInput + " is a valid palindrome.");
        } else {
            // 输出所有不匹配的位置
            for (String pair : mismatchPairs) {
                System.out.printf("The characters at %s do not match.%n", pair);
            }
            System.out.println(stringInput + " is not a valid palindrome.");
            System.out.println("number of invalid character matches: " + mismatchCount);
        }
        keyboard.close();
    }
}

关键逻辑说明

  1. 双指针遍历:用left从字符串头部、right从尾部同时向中间移动,逐字符对比,直接获取每一组不匹配的索引位置。
  2. 信息记录:用List存储所有不匹配的索引对,用mismatchCount统计不匹配的总组数。
  3. 格式输出:遍历List输出每个不匹配的位置,再按要求输出回文判断结果和计数。

比如输入goop,程序会输出:

The characters at index 0 and 3 do not match.
goop is not a valid palindrome.
number of invalid character matches: 1

内容的提问来源于stack exchange,提问作者Brooke Cruz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 07:10:15