Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string
分析:将一句英文中单词倒序后输出
思路:用空格符将单词分开,倒序后再重新组装。关于单词倒序,可以先转成charArray后逆序组装,但oj会报time limit exceeded Last executed input:
即算法复杂度过高。这里JAVA中使用StringBuffer的reverse方法即可
JAVA CODE
class Solution { public String reverseWords(String s) { String[] ss = s.split(" "); s = ""; for (int i = 0; i < ss.length; i++) { StringBuffer stringBuffer = new StringBuffer (ss[i]); stringBuffer = stringBuffer.reverse(); s += stringBuffer; if (i != ss.length - 1) s += " "; } return s; } }