题目描述:
- 判断一个是否是回文字符串。回文字符串是指正序(从左向右)和倒序(从右向左)读都是一样的字符串。
示例1
- 输入:abc
- 输出:false
示例2
- 输入:-121
- 输出:false
示例3
- 输入:abba
- 输出:true
判断是否为回文字符串代码
public static void main(String[] args) { String str= "abba"; char[] strs= str.toCharArray (); System.out.println (isTure (strs)); } // 判断是否为回文字符串 private static Boolean isTure(char[] strs) { // 字符的长度 int len = strs.length; // 左右比较时的下标 int m = 0, n = 0; // 定义初始化位置 int start = len >> 1; // 奇数时m=n=start,偶数时m=start,n=start-1 m = ((len & 1) == 1) ? (n = start) : ((n = start -1) + 1); // 循环直到比较完最后一个字符,或者程序判断出不是回文字符串,结束 while (n >= 0 && m <= len) { if (strs[n] != strs[m]) return false; m++; n--; } return true; }
字符串反转的方式(一)
- 倒叙遍历+新char[]存储
public static void main(String[] args) { String str = "abba"; // 转化为char字符数组 char[] chars = str.toCharArray (); // 创建一个新的char字符数组 char[] newChars = new char[chars.length]; // 记录新的char数组的脚标 int index = 0; // for循环倒叙将字符放入新的char数组中 for (int i = chars.length - 1; i >= 0; i--) { newChars[index] = chars[i]; index++; } // 将char数组转化为string字符串 String newStr = new String (newChars); // 比较字符串是否一致 System.out.println (str.equals (newStr)); }
字符串反转的方式(二)
- 在原char[]直接两两替换
public static void main(String[] args) { String str = "aba22aba"; char[] chars = str.toCharArray (); int len = chars.length; for (int i = 0, j = len - 1; i < len; i++, j--) { if (i == (len >> 1)) break; char temp = chars[i]; chars[i] = chars[j]; chars[j] = temp; } System.out.println (str.equals (new String (chars))); }