private final String str = "Monday";
/**
* 时间复杂度:O(n)
* 空间复杂度O(1)
*/
@Test
public void t1() {
String ans = "";
for (int i = str.length() - 1; i >= 0; i--) {
ans += str.charAt(i);
}
System.out.println(ans);
}
/**
* 时间复杂度:O(n)
* 空间复杂度O(1)
*/
@Test
public void t2() {
char[] arrs = str.toCharArray();
String ans = "";
for (int i = arrs.length - 1; i >= 0; i--) {
ans += arrs[i];
}
System.out.println(ans);
}
/**
* 时间复杂度:O(N/2)=O(n),从字符串中间开始,向左右推开,逐个交换
* 空间复杂度O(1)
*/
@Test
public void t3() {
StringBuffer buffer = new StringBuffer(str);
System.out.println(buffer.reverse());
}
/**
* 时间复杂度:O(logN),二分
* 空间复杂度O(1)
*/
@Test
public void t4() {
String rev = reverseStr(str);
System.out.println(rev);
}
private String reverseStr(String str) {
if (str.length() <= 1) {
return str;
}
String left = str.substring(0,str.length()/2);
String right = str.substring(str.length()/2,str.length());
return reverseStr(right) + reverseStr(left);
}
网友评论