It is observed that I am decrementing the counter in the for-loop. Why is that? It is simply because I want to start to look at the given string in a backward manner. A StringBuffer is used to append the letters because append() operation is not as costly as we would have used a string and concatenate the letters. Simple isn't it? Many of us might thought that we could have used the reverse() method instead, rather than coding this unnecessarily. I would say this suggested solution is very reliable if we are looking at solving this problem more discretely.
public static String reverseCharacters(String text){
StringBuffer reversed = new StringBuffer();
int len = text.length()-1;
for (int i=len; i>=0; i--) {
reversed.append(text.charAt(i));
}
return reversed.toString();
}
Next we will explore how to reverse a string by words. Once again I am suggesting the cheapest way to solve it. Some of us might thought that we have to first split the strings by a whitespace and then push the words into a stack, which we will then pop every single item out from the stack. Here is my approach in solving it using very little copying and no temporary variables.
I am looking backwards again. This time it is the array of split texts. I am splitting the text using the split() method and provide a regular expression statement [\s*]. The StringBuffer is used instead of String because it is less costly to append strings using the append() method. The method reverseWords() returns "sky blue clear very" if the given string is "very clear blue sky".
public static String reverseWords(String text) {
StringBuffer reverse = new StringBuffer();
String[] textArray= text.split("[\\s*]");
int len = textArray.length-1;
for (int i=len; i>=0; i--) {
reverse.append(textArray[i]).append(" ");
}
return reverse.toString();
}
0 comments:
Post a Comment