一个简单的算法题,有如下3中解决办法:
public class ReverseTest {
public static void main(String[] args) {
String str = "abcdefg";
// String reverse = reverse1(str,2,5);
// String reverse = reverse2(str,2,5);
String reverse = reverse3(str,2,5);
System.out.println(reverse);
}
// 方式一:根据索引遍历交换
public static String reverse1(String str, int startIndex, int endIndex){
if (str != null) {
char[] ch = str.toCharArray();
for (int x = startIndex, y = endIndex; x < y; x++, y--) {
char temp = ch[x];
ch[x] = ch[y];
ch[y] = temp;
}
return new String(ch);
}
return null;
}
// 方式二:根据索引将其分为三部分
public static String reverse2(String str, int startIndex, int endIndex){
if (str != null) {
char[] ch = str.toCharArray();
// 第一部分
String s = str.substring(0,startIndex);
// 第二部分
for (int i = endIndex; i >= startIndex; i--) {
s += str.charAt(i);
}
// 第三部分
s += str.substring(endIndex + 1);
return s;
}
return null;
}
// 方式三:同第二种方法,使用 StringBuilder/StringBuffer 替换 String
public static String reverse3(String str, int startIndex, int endIndex) {
if (str != null) {
StringBuilder builder = new StringBuilder(str.length());
// 第一部分
builder.append(str.substring(0, startIndex));
// 第二部分
for (int i = endIndex; i >= startIndex; i--) {
builder.append(str.charAt(i));
}
// 第三部分
builder.append(str.substring(endIndex + 1));
return builder.toString();
}
return null;
}
}
要将学会的知识付予运用,否则迟早会忘却!!!