题目: 编写一个isPalindrome的方法,检测一个单词是否是回文单词。
说明: abcbc,otto等均为回文单词。
java程序:
package Palindrome;
public class Palindrome {
public static void main(String[] args) {
String s = "2112";
// first(s);
// last(s);
// middle(s);
System.out.println(isPalindrome(s));
}
//输出首字母
public static void first(String s) {
System.out.println(s.charAt(0));
}
//输出末字母
public static void last(String s) {
System.out.println(s.charAt(s.length()-1));
}
//输出出首尾字母外的其他字母
public static void middle(String s) {
System.out.println(s.substring(1,s.length()-1));
}
//判断是否是回文单词
public static boolean isPalindrome (String s) {
int n = s.length();
int flag = 1;
for (int i=1; i<n/2; i++) {
if (s.charAt(i-1)!=s.charAt(s.length()-i)) {
flag = 0;
break;
}
}
if (flag==1) {
return true;
}else {
return false;
}
}
}
- 1、这个程序主要使用字符串的几个方法,包括.charAt() ,length() .subString( , )
- 2、在判断是否为回文时,根据第一个对应倒数第一个,第二个对于倒数第二个的方式进行比较,默认标志位为1,当发现不一样时,标志位变为0,最后检测标志位进行判断。