Skip to content

Instantly share code, notes, and snippets.

@TonnyXu
Created February 27, 2010 13:36
Show Gist options
  • Save TonnyXu/316690 to your computer and use it in GitHub Desktop.
Save TonnyXu/316690 to your computer and use it in GitHub Desktop.
package basic.java;
interface Reverse{
public String reverse(String s);
}
class ReverseByArray implements Reverse{
public String reverse(String s){
if (null == s || s.equals("")) return s;
char[] charArray = s.toCharArray();
int halfLength = s.length() >> 1;
for (int i = 0; i < halfLength; i++) {
charArray[i] ^= charArray[s.length() - i -1];
charArray[s.length() -i -1] ^= charArray[i];
charArray[i] ^= charArray[s.length() - i -1];
}
return new String(charArray);
}
}
class ReverseByArray2 implements Reverse{
public String reverse(String s){
if (null == s || s.equals("")) return s;
char[] value = s.toCharArray();
int count = s.length() ;
int n = count - 1;
for (int j = (n-1) >> 1; j >= 0; --j) {
char temp = value[j];
char temp2 = value[n - j];
value[j] = temp2;
value[n - j] = temp;
}
return new String(value);
}
}
class ReverseByAPI implements Reverse{
public String reverse(String s){
if (null == s || s.equals("")) return s;
return new StringBuffer(s).reverse().toString();
}
}
public class StringReverse {
public static void checkIntegrity(Reverse Obj, String objDesc, String s){
System.out.println("Original String:" + s);
System.out.printf("Reversed String: %1$s(%2$s)\n", Obj.reverse(s), objDesc);
}
public static String stringOfLength(int l){
if (0 >= l) return "";
double random;
int index = 0;
char[] c = new char[l];
long cint;
while (index < l){
random = Math.random();
cint = Math.round(26*random) + 65;
c[index] = Character.forDigit((int)cint, Character.MAX_RADIX);
index++;
}
return new String(c);
}
public static void benchmark(Reverse obj, String objDesc, String s, int length){
long start = System.nanoTime();
for(int i=0; i<10000; i++){
obj.reverse(s);
}
long end = System.nanoTime();
System.out.printf("%1$d ns, %2$s (10000 times, length:%3$d)\n", (end-start), objDesc, length);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ReverseByArray rba = new ReverseByArray();
ReverseByArray2 rba2 = new ReverseByArray2();
ReverseByAPI rbapi = new ReverseByAPI();
String[] testArray = {
"1234567890",
"123",
"僕らの日本語"
};
for (String s : testArray) {
checkIntegrity(rba, "Reverse by array", s);
checkIntegrity(rba2, "Reverse by array 2", s);
checkIntegrity(rbapi, "Reverse by api", s);
System.out.println("--------");
}
int[] length = {3,10,100,1000,10000,50000};
for (int l : length) {
String s = stringOfLength(l);
benchmark(rba, "Reverse by array", s, l);
benchmark(rba2, "Reverse by array 2", s, l);
benchmark(rbapi, "Reverse by API",s, l);
System.out.println("--------");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment