1. 程式人生 > 其它 >判斷迴文字串

判斷迴文字串

技術標籤:什麼是迴文字串如何判斷迴文字串java

問題描述:如何判斷迴文字串?

什麼是迴文字串?
如果一個字串從前向後讀和從後向前讀,都是一個字串稱為迴文字串。
例如:mom,dad,opo等。

package work_15;

import java.util.Scanner;

public class Test07 {
    //迴文字元有一個特點就是第一個字元一定等於最後一個字元,
    public static void main(String[] args) {
        Scanner sr = new Scanner(System.in);
        System.
out.println("請輸入要檢驗的字串:"); String next = sr.nextLine(); boolean huiwen = Ishiwen(next); System.out.println("是否是迴文字串:"+huiwen); } private static boolean Ishiwen(String str) { //star為開始,end為結束 int start = 0; int end = str.length()-
1; while (start < end){//肯定開始下標小於結束下標 //通過比較正數第一個字元和倒數第一個字元是否相等, //比較正數第二個字元和倒數第二個字元是否相等... //來判斷是不是迴文字元 if(str.charAt(start) != str.charAt(end)){ return false; } //通過start++來實現,下標向後移動。 start++; //通過end--來實現,下標向前移動。
end--; } return true; } }