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.
下面是我开始的代码和修改过后的代码。
首先要能够分离出单词, 然后把分离出来的单词reverse之后拼接成大的字符串。
鉴于我初学java,很多方便好用的函数都不了解,这版代码写的很蠢,虽然结果正确但是内存超限。好了,开始说我的方法。根据空格分离出单词,所以我首先遍历了字符串记录下了空格的位置,这样可以找出每个单词的起始位置,将单词reverse之后放到新的字符串中添加空格进行拼接。这样做很费力,因为开头和结尾的单词并不是两边都有空格,需要单独处理。下面就是这个思路的代码:
class Solution {
public String reverseWords(String s) {
int n = s.length();
int[] blank = new int[n];
int count = 0;
for(int i=0; i<n; i++){
if(s.charAt(i)==' ')
blank[count++] = i;
}
String res = "";
if(count>0){
for(int i=0; i<count; i++){
if(i==0){
for(int j=blank[i]-1; j>=0; j--){
res += s.charAt(j);
}
res += " ";
}
else{
for( int j=blank[i]-1; j>blank[i-1]; j--){
res += s.charAt(j);
}
res += " ";
}
}
for(int i=n-1; i>blank[count-1]; i--)
res += s.charAt(i);
}
else{
for(int i=n-1; i>=0; i--)
res += s.charAt(i);
}
return res;
}
}
这个代码并没有被AC,于是我去看了Solution。发现了好多很好用的函数,split函数可以将字符串分割成一个字符串数组,reverse函数可以反转字符串,这些我都是用遍历的方法实现的,太蠢了。
import java.util.*;
class Solution {
public String reverseWords(String s) {
String res = "";
String[] sarray = s.split(" ");
for(int i=0; i<sarray.length; i++){
res += new StringBuffer(sarray[i]).reverse().toString() + " ";
}
return res.trim();
}
}
在LeetCode上做题收获太多了,继续坚持!