public static void main(String[] args) {
String str = "levelnoonabcba";
HuiWen h = new HuiWen();
System.out.println(h.isOrNot(str));
}
private int isOrNot(String str) {
// 字符串放入数组
char[] a = str.toCharArray();
int index;
int result = 0;
for (int i = 0; i < a.length; i++) {
char t = a[i];
// a字符数组,t遍历数组,i+1当前位置加1,数组长度
if ((index = find(a, t, i + 1, a.length - 1)) != -1) {
if (allOk(a, i, index) != -1) {
result += 1;
}
}
}
return result;
}
// 找到字符串中与第i个字符串中相等的字符串对应的下标
public static int find(char A[], char x, int lo, int hi) {
int i = 0;
for (i = lo; i <= hi; i++) {
if (A[i] == x) {
return i;// 找到输出下标
}
}
return -1;// 未找到,输出-1
}
// 判断整个字符串是否是回文
public int allOk(char A[], int start, int end) {
System.out.println(start);
int k = 0;
int i;
for (i = start; i <= end / 2; k++, i++) {
if (A[i] != A[end - k]) {
return -1;
}
}
return 1;
}
2,八皇后问题
public class EightQueen {
static int n = 8, count;
public static void main(String[] args) {
int[][] chess = new int[n][n];
// 棋盘赋值
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
chess[i][j] = 0;
}
}
putChess(0, chess);
}
// 行row,临时棋盘
public static void putChess(int row, int[][] cChess) {
int[][] currentChess = (int[][])cChess.clone();
if (row == n) {
count++;
System.out.println("第" + count + "种");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(currentChess[i][j]);
}
System.out.println();
}
System.out.println();
} else {
for (int i = 0; i < n; i++) {
if (!isDanger(row, i, currentChess)) {
for (int j = 0; j < n; j++) {
currentChess[row][j] = 0;
}
currentChess[row][i] = 1;
putChess(row + 1, currentChess);
}
}
}
}
// 判断棋子是否可以下,只需要判断棋盘上的,row行,col列
public static boolean isDanger(int row, int col, int[][] currentChess) {
for (int i = 0; i < row; i++) {
if (currentChess[i][col] == 1)
return true;
// 判断对角线公式 y=-x + b 和 y = x -b
for (int j = 0; j < n; j++) {
if (((row + col) == (i + j) || (row - col) == (i - j)) && currentChess[i][j] == 1)
return true;
}
}
// 不危险,可以下棋
return false;
}