假设我输入“在你看到厄尔巴之前你有能力”。这看起来像回文,直到您看到“were”中的第一个“e”,因此此文本的输出将是:这不是在:ablewe检测到的回文不匹配
下面是司机
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String line;
do {
// prompt user for input String and store it in line
System.out.print("Enter an expression (or hit Enter to exit) : ");
line = input.nextLine();
// convert input String to upper case
line = line.toUpperCase();
// if user hits Enter or simply types in spaces and hits enter, break out of loop
if (line.trim().isEmpty()) {
break;
}
// call isPalindrom
// if it returns true, display one message, else display another
if (Palindrome.isPalindrome(line)) {
System.out.println("Your expression is a palindrome.");
} else {
System.out.println("Your expression is not a palindrome.");
}
} while (line.length() != 0);
System.out.println("You didn't enter an expression. Exiting application ...");
}
}
下面是具有isAlindrome方法的类
public static boolean isPalindrome(String input){
// create Queue and Stack of Characters
// to store the input String
Queue<Character> q = new LinkedList<>();
Stack<Character> s = new Stack();
// temporarily store the individual Characters
// in input String before they're pushed onto
// Stack and added to Queue
Character letter;
// keep track of differences between Characters
// in Stack and Queue
int mismatches = 0;
// loop through input String
for (int i = 0; i < input.length(); i++){
// get current Character
letter = input.charAt(i);
// if the current Character is an alphabetic character
if (Character.isLetter(letter)){
// push it onto the Stack
s.push(letter);
// add it to the Queue
q.add(letter);
}
}
// while the Queue isn't empty
while (!q.isEmpty()){
// remove a Character from the Queue
// pop a Character from the Stack
// if they're not equal, increment mismatches
if (!q.remove().equals(s.pop()))
// Stack will produce the input String backwards
// Queue will produce the input String forwards
mismatches++;
}
// return true if there are no mismatches, else return false
return (mismatches == 0);
}
}
我需要输出来显示不匹配发生的位置
1条答案
按热度按时间snz8szmq1#
创建字符串(
allLetters
在下面给出的代码中)用空字符串替换所有非字母,即。input.replaceAll("[^\\p{L}]", "")
哪里^\\p{L}
指定非字母字符。使用变量(
index
在下面给出的代码中)跟踪已处理的字母的位置。当检测到不匹配时,打印allLetters.substring(0, index + 1)
打破循环。代码:
示例运行:
注意:当前,您正在将转换为大写的用户输入传递给函数,
isPalindrome
因此输出字符串(ABLEWE
在上面显示的示例运行中)是大写的。换个案子的好地方应该在里面isPalindrome
如下所示:示例运行: