package leetcode.algorithm;
/**
* @author lkl
* 20180201
*/
/*
* Subject:
* Given an input string, reverse the string word by word.
* For example:
* Given s = "the sky is blue"
* return "blue is sky the".
*/
public class ReverseWordsInaString {
public static void main(String[] lkl) {
String str = "the sky is blue";
System.out.print(reverseWords(str));
}
/*
* 方法:使用split()方法将字符串按照空格分割,并将分割后的元素通过递减的方式逐个放入数组中放入,return返回结果即可
*/
public static String reverseWords(String str) {
StringBuilder reverseResult = new StringBuilder();
String[] words = str.split("\\s+|\\t");//考虑出现多个空格或Tab键的情况
for (int i = words.length - 1; i >= 0; i--) {
reverseResult.append(words[i]).append(' ');
}
return reverseResult.toString().trim();
}
}