設計思路:
遞歸判斷 字符串的首尾位置的字符是否一樣。
遇到的問題:
用 Scanner input=new Scanner(System.in);
實例化一個對象,用完不關閉會一直占用資源,編譯時會警告。
應關閉 :input.close();
源代碼:
package Huiwen;
import java.util.*;
public class Palindrome
{
public static void main(String[] args)
{
System.out.println("請輸入一個字符串:");
Scanner input=new Scanner(System.in); //掃描從控制台輸入的字符
String str=input.nextLine(); //輸入字符串
int n=str.length();
int m=JudgePalindrome(str,n);
if(m==1)
System.out.println("該字符串回文");
else
System.out.println("該字符串不回文");
input.close();
}
public static int JudgePalindrome(String str,int n)
{
int s,w;
int j=0;
char c1,c2;
s=str.length()-n;//第一個字符的位置
w=n-1;//最后一個字符的位置
c1=str.charAt(s);//stringObject.charAt(index) 方法可返回指定位置的字符
c2=str.charAt(w);//字符串中第一個字符的下標是 0。如果參數 index 不在 0 與 string.length 之間,該方法將返回一個空字符串。
if(c1==c2||s==w)
j=1;
if(s!=w&&s<w&&j==1)
JudgePalindrome(str,n-1);
return j;
}
}
運行結果截圖: