mine
public static String reverseWords(String s) {
if(s.length() == 0){
return "";
}
ArrayList<Character> result_list = new ArrayList<Character>();
Stack<Character> result_stack = new Stack<Character>();
boolean flag_KongGe = false;
for(int i = s.length() - 1; i >= 0; --i){
if(s.charAt(i) == ' '){
while(result_stack.size() > 0){
result_list.add(result_stack.pop());
flag_KongGe = true;
}
if(flag_KongGe){
result_list.add(' ');
flag_KongGe = false;
}
}else{
result_stack.push(s.charAt(i));
}
}
while(result_stack.size() > 0){
result_list.add(result_stack.pop());
}
if(result_list.size() == 0){
return "";
}
for(int i = result_list.size() - 1;result_list.get(i) == ' ' ; --i){
result_list.remove(result_list.size() - 1);
}
char[] result_char_array = new char[result_list.size()];
for(int i = 0; i < result_char_array.length; ++i){
result_char_array[i] = result_list.get(i);
}
return String.valueOf(result_char_array);
}
Clean Code Hand Book
public String reverseWords(String s) {
StringBuilder reversed = new StringBuilder();
int j = s.length();
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == ' ') {
j = i;
} else if (i == 0 || s.charAt(i - 1) == ' ') {
if (reversed.length() != 0) {
reversed.append(' ');
}
reversed.append(s.substring(i, j));
}
}
return reversed.toString();
}