1. 程式人生 > >課後作業3:使用遞歸方法判斷某個字串是否是回文

課後作業3:使用遞歸方法判斷某個字串是否是回文

put 設計思想 ring () static rgs png [] 輸出

【程序設計思想】

要判斷一串字符串,首先將前面和後面的每個字符表示出來,然後判斷,如果還沒有到最中間那兩個字符,就一直調用函數來判斷,最後將結果輸出。

【程序流程圖】

技術分享

【源程序】

//那穎 信1605-2班 20163448
import java.util.*;
public class Palindrome
{
public static void main(String[] args)
{
System.out.println("please input a string of Characters:");
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("這個字符串不是回文字符串");

}

public static int JudgePalindrome(String str,int n)
{
int a,b,j=0;
char c1,c2;
a=str.length()-n;
b=str.length()-(a+1);
c1=str.charAt(a);
c2=str.charAt(b);
if(c1==c2||a==b)
j=1;
if(a!=b&&a<b&&j==1)
JudgePalindrome(str,n-1);
return j;
}
}

【運行結果截圖】

技術分享

課後作業3:使用遞歸方法判斷某個字串是否是回文