前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
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"这个题目还是蛮简单的,可以先split,然后再reverse。
public class Solution {
public String reverseWords(String s) {
if(s.length() == 0) return s;
String[] words = s.split(" ");
StringBuffer sb = new StringBuffer("");
for(String word : words){
for(int i = word.length() - 1 ;i >= 0; i --) sb.append(word.charAt(i));
sb.append(" ");
}
sb.setLength(sb.length() - 1);
return sb.toString();
}
}