Last active
August 29, 2015 14:02
-
-
Save UncleGarden/85509dad7178cde74c50 to your computer and use it in GitHub Desktop.
CareerCup 150
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 1.2 Implement a function void reverse(char* str) in C or C++ which reverses a | |
* null-terminated string. | |
* | |
* @author Jiateng | |
*/ | |
public class CC1_2 { | |
//Time O(n), Space O(n) | |
public static String reverse1(String target) { | |
StringBuilder result = new StringBuilder(); | |
//directly add from the end to the start | |
for (int i = target.length() - 1; i >= 0; i--) { | |
result.append(target.charAt(i)); | |
} | |
return result.toString(); | |
} | |
//Time O(n), Space O(1) | |
public static String reverse2(String target) { | |
//make an array | |
char[] array = target.toCharArray(); | |
//start | |
int left = 0; | |
//end | |
int right = array.length - 1; | |
while (left < right) { | |
//swap | |
char temp = array[right]; | |
array[right] = array[left]; | |
array[left] = temp; | |
//move from both start and end to the middle | |
left++; | |
right--; | |
} | |
return String.valueOf(array); | |
} | |
public static void main(String[] args) { | |
String target = "sodufhosdg"; | |
System.out.println(reverse1(target)); | |
System.out.println(reverse2(target)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In StringBuffer type, there is a reverse() method to fast reverse the stringBuffer.