版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/82857511
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.
样例
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
注意事项
In the string, each word is separated by single space and there will not be any extra space in the string.
解题思路:
先用空格对字符串进行分割,然后对每个字符进行翻转,注意翻转方法reverse()只有StringBuilder与StringBuffer才有。而trim()方法只有String才有,不要记混了。
public class Solution {
/**
* @param s: a string
* @return: reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order
*/
public String reverseWords(String s) {
// Write your code here
String[] strs = s.split(" ");
StringBuilder res = new StringBuilder();
for(String str : strs){
res.append(new StringBuilder(str).reverse());
res.append(" ");
}
return res.toString().trim();
}
}