Created
March 30, 2015 18:58
-
-
Save michaelniu/9b235951549bdc561320 to your computer and use it in GitHub Desktop.
cc150-1.2
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
public class ReverseString_1_2 { | |
/*1.2 Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters, including the null character.) | |
* Nothing special to exchange the i to string lenghth -i-1 by useing stringbuilder | |
* O(n) space O(1) | |
* */ | |
public static void main(String[] args ) { | |
String test= "879-4uiordedpu;"; | |
System.out.println(reversString(test)); | |
} | |
public static String reversString(String str){ | |
if(str==null || str.trim().length() == 0) | |
return str; | |
StringBuilder result=new StringBuilder(str); | |
for(int i =0; i<=str.length()/2;i++){ | |
char temp = str.charAt(i); | |
result.setCharAt(i, str.charAt(str.length()-1-i)); | |
result.setCharAt(str.length()-1-i, temp); | |
} | |
return result.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment