package com.hawk.test;
//java代码实现回文串
public class Testisreserve {
// 1:字符串倒置后逐一比较法
public static Boolean testIsreverse1(String str) {
StringBuffer sb = new StringBuffer(str);
StringBuffer reverse = sb.reverse();// 把字符串反转
int count = 0;
for (int i = 0; i < str.length(); i++) {
//charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1
if (str.charAt(i) == sb.charAt(i)) {
count++;
}
}
if (count == str.length()) {
return true;
} else {
return false;
}
}
//:2:字符串倒置后创建新字符串,两字符串直接比较法
public static Boolean testIsreverse2(String str) {
StringBuffer sb = new StringBuffer(str);
sb.reverse();// 把字符串反转
String newsb = new String(sb);
if (str.equals(newsb)) {
return true;
} else {
return false;
}
}
//:3: 字符串首尾元素对比法
public static Boolean testIsreverse3(String str) {
int i;
int j = str.length() - 1;
//split() 方法用于把一个字符串分割成字符串数组

String[] strings = str.split("");// 字符串拆分
for (i = 0; i <= j; i++, j--) {
if (!strings[i].equals(strings[j])) {
return false;
}
}
return true;
}
// 字符串首尾元素对比法
public static void main(String[] args) {
String str = "12321";
Boolean boolean1 = testIsreverse3(str);
}
}
浙公网安备 33010602011771号