如何识别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(); } }
关键逻辑说明
- 双指针遍历:用
left从字符串头部、right从尾部同时向中间移动,逐字符对比,直接获取每一组不匹配的索引位置。 - 信息记录:用
List存储所有不匹配的索引对,用mismatchCount统计不匹配的总组数。 - 格式输出:遍历
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
相关产品推荐
相关产品推荐

