使用遞歸方式判斷某個字串是否是回文:
回文是指正着讀、反着讀都一樣的句子。比如“我是誰是我”
用到charAt()方法,例如下面的例子:charAt() 方法用於返回指定索引處的字符。索引范圍為從 0 到 length() - 1。
語法:
public char charAt(int index)
參數
-
index -- 字符的索引。
返回值
返回指定索引處的字符。
public class Test { public static void main(String args[]) {
String s = "www.runoob.com";
char result = s.charAt(8);
System.out.println(result);
}
}
String s = "www.runoob.com";
char result = s.charAt(8);
System.out.println(result);
}
}
以上程序執行結果為:
o
判斷是否是回文,首先用戶輸入一段字符串,然后先判斷字符串的長度,如果長度為零或一,則必是回文,若長度大於等於2,則先判斷第一個字符與最后一個字符,相等則截取第二個到倒數第二個,再判斷,利用遞歸方法。
//源代碼
package lianxi1;
import java.util.*;
public class Palindrome {
import java.util.*;
public class Palindrome {
static public boolean isPa(String f,int n){
if(f.charAt(0)==f.charAt(f.length()-1)) {
if(f.length()>2) {
return isPa(f.substring(n+1,f.length()-1),0); //從n+1到(f.length()-1)-1
}
else {
return true;
}
}
else return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
if(f.charAt(0)==f.charAt(f.length()-1)) {
if(f.length()>2) {
return isPa(f.substring(n+1,f.length()-1),0); //從n+1到(f.length()-1)-1
}
else {
return true;
}
}
else return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
System.out.println("請輸入字符串:");
String f = scan.next();
if(isPa(f,0)) {
System.out.println("字符串: " + f + " 是回文串");
}
else {
System.out.println("字符串: " + f + " 不是回文串");
}
}
System.out.println("請輸入字符串:");
String f = scan.next();
if(isPa(f,0)) {
System.out.println("字符串: " + f + " 是回文串");
}
else {
System.out.println("字符串: " + f + " 不是回文串");
}
}
}