Skip to content

Instantly share code, notes, and snippets.

@startupjing
Created June 16, 2014 05:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save startupjing/8f8a5adc6ed5408923a1 to your computer and use it in GitHub Desktop.
Save startupjing/8f8a5adc6ed5408923a1 to your computer and use it in GitHub Desktop.
my solutions--cc150 1.2
import java.util.Scanner;
public class ReverseStr {
/**
* ask for user input and reverse the input string
* @param args
*/
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a string (q to quit): ");
while(input.hasNextLine()){
String userStr = input.nextLine();
if(userStr.equals("q")){
System.out.println("quit...");
System.exit(0);
}
System.out.println("The reversed string is " + reverse(userStr));
System.out.println();
System.out.println("Please enter another string (q to quit): ");
}
}
/**
* reverse the given string
* @param s
* @return reversed string
*/
public static String reverse(String s){
StringBuffer result = new StringBuffer();
for(int i=s.length()-1; i>=0; i--){
result.append(s.charAt(i));
}
return result.toString();
}
}
@monkerek
Copy link

In this case the space complexity should be O(n), n equals the length of the input string.
This is because you allocate a buffer to store the output string.

@startupjing
Copy link
Author

Thxs

@jyuan
Copy link

jyuan commented Jun 23, 2014

Actually, The StringBuffer has a reverse() method to fast implements this requirement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment