-
-
Save startupjing/8f8a5adc6ed5408923a1 to your computer and use it in GitHub Desktop.
my solutions--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
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(); | |
} | |
} |
Thxs
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
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.