这个问题说起来很简单,但是我却忘了怎么做,想到了递归。递归不是一个好办法。
感悟颇多,很长一段时间没有想过这些问题了。
好了,废话不多说了。我们上来贴代码。
public class ArrayConvert {
private static String orderDesc(String str) {
if (str == null || str.length() < 0) {
return "error";
}
byte[] bytes = str.getBytes();
int N=bytes.length;
for (int i = 0; i < bytes.length / 2; i++) {
Byte b = bytes[i];
bytes[i] = bytes[N- 1 - i];
bytes[N - 1 - i] = b;
}
return new String(bytes);
}
//第二种使用了递归
private static String orderDesc2(String str) {
if (str == null || str.length() < 0) {
return "error";
}
if (str.length() == 1 || str.length() == 0) {
return str;
}
char a = str.charAt(0);
char b = str.charAt(str.length() - 1);
if (str.length() == 2) {
return b + "" + a;
}
return b + orderDesc2(str.substring(1, str.length() - 1)) + a;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = orderDesc("123456");
System.out.println(str);
}
}
第三种来自于算法4 P114 也是递归实现
public static String mystery(String s) {
if (s == null) {
return null;
}
if (s.length() <= 1) {
return s;
}
//这样理解,当最终是两个字符的时候把位置互换即可。所以是一种逼近思想。类似于快速排序。
//先分成两个部分,然后在继续再分成两个部分。直到不可再分然后合并。
String a = s.substring(0, s.length() / 2);
String b = s.substring(s.length() / 2, s.length());
return mystery(b) + mystery(a);
}
2、判断是否是回文数。
public class Page116 {
//递归实现
public boolean find(String s) {
if (s.length() <= 1) {
return true;
} else if (s.charAt(0) == s.charAt(s.length() - 1)) {
return find(s.substring(1, s.length() - 1));
} else {
return false;
}
}
//普通实现
public boolean find2(String s) {
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == s.charAt(s.length() - 1 - i)) {
continue;
} else {
return false;
}
}
return true;
}
public static void main(String[] args) {
Page116 c = new Page116();
// System.out.println(c.find("123321"));
System.out.println(c.find2("1234321"));
}
}