-2
我已經寫了一個程序,檢查兩個字符串是否是迴文。如果他們不是,那麼它會告訴哪些字符不匹配。代碼是:java程序顯示字符串是迴文,也顯示是否不是哪個字符不匹配
public void checkPalindrom() {
boolean success = true; // success indicates whether palindrome or not
boolean done = false; // it is used to stop the while loop
int i = 0; // i wil be used as an index of the inputString
while (!done) {
// until the end of inputString or it encounters '#' character
// take each character in inputString from left and add it to charStack and charQueue
while (true) {
if (i == inputString.length())
break;
else if (inputString.charAt(i) == '#') {
break;
}
char ch = inputString.charAt(i);
charStack.push(ch);
charQueue.add(ch);
++i;
}
// prints out the substring extracted from the input string using queue's toString method
System.out.print("The input " + charQueue.toString());
// until the charQueue or charStack becomes empty
// remove a character from each of charStack and charQueue, and check if they are same.
// If they are different, then print out the approproate message (" is not a palindrome\n")
// and also print which first set of two characters are different
// ("The characters ' ' and ' ' do not match\n\n") -- note that you need to print
// two such characters inbetween ' '
// Also set success to false, so that the following "if" statement will be skipped
char ch1, ch2;
success = true;
while (!charQueue.isEmpty()) {
ch1 = charQueue.pop();
ch2 = charStack.pop();
if (ch1 != ch2) {
System.out.print(" is not a palindrome \nThe characters '" + ch1 + "' and '" + ch2 + "' do not match\n\n");
success = false;
break;
}
}
if (success == true)
System.out.print(" is a palindrome\n\n");
// i reaches the end of string, it is done processing the inputString
if (i == inputString.length())
done = true;
else {
i++;
success = true; // set it back to true for the next substring to check
}
} // end of while loop
} // end of checkPalindrome() method
我沒有得到預期的輸出和它的一些案件的失敗。任何人都可以請幫我解決這個算法。
感謝
你可以舉一個這樣的具體案例嗎?它在哪裏工作,它不在哪裏?... –
如果兩者的長度不同,並且因此不是迴文,您會返回哪個索引? – thebenman
@thebenman堆棧和隊列來自同一個輸入字符串,所以它們的大小始終相同。 –