java迴文代碼

import java.util.*;java

import java.math.BigInteger;數組

import java.util.Scanner;ui

public class Test{    設計

         static Scanner a=new Scanner(System.in);blog

         static char str[] = new char[99];字符串

         static int l=0;class

         public static void main(String[] args) {import

                  System.out.println("請輸入字符串:");im

                  String b = a.next();next

                  for(int i=0;i<b.length();i++) {//字符數組

                          str[l] = b.charAt(i);

                          l++;

                  }

                  boolean hw = Huiwen(str, 0, l-1,l);

                  if(hw) {

                          System.out.println("是迴文");

                  }

                  else

                  {

                          System.out.println("不是是迴文");

                  }

         }

         public static boolean Huiwen(char a[],int first,int end,int length){

                  if(length == 1 || length == 0)

                          return true;

                  if (a[first] != a[end] || first >= end) {//第一個字符與最後一個字符比較

                          return false;

                  }

                  return Huiwen(a, first + 1, end -1,length -2);//兩邊靠攏

         }

 

         }

 

 

設計思路:將字符串存入一個數組中,在讓第一個字符和最後一個字符對比,若是發現不同,則不是迴文,若是同樣則在向中間靠攏,直到字符長度爲一或者爲0;

相關文章
相關標籤/搜索