使用自带的split和reverse
//11ms
public static String reverseWords(String s) {
String[] words = s.split(" ");
StringBuilder res =new StringBuilder();
for (String word:words) {
res.append(new StringBuilder(word).reverse()+" ");
}
return res.toString().trim();
}
//我自己写的
//58ms
public static String reverseWords1(String s) {
String[] words = s.split(" ");
StringBuilder bud =new StringBuilder();
for (int i = 0; i <words.length ; i++) {
String temp = "";
for (int j = words[i].length() - 1; j >= 0; j--) {
temp +=words[i].charAt(j);
}
bud.append(temp+" ");
}
return bud.toString().trim();
}
我们可以自己写一个 split 和 reverse 函数。 split 函数将字符串按照 " " (空格)为分隔符将字符串分开并返回单词列表。 reverse 函数返回每个字符串反转后的字符串。
//32ms
public String reverseWords(String s) {
String words[] = split(s);
StringBuilder res=new StringBuilder();
for (String word: words)
res.append(reverse(word) + " ");
return res.toString().trim();
}
public String[] split(String s) {
ArrayList < String > words = new ArrayList < > ();
StringBuilder word = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
words.add(word.toString());
word = new StringBuilder();
} else
word.append( s.charAt(i));
}
words.add(word.toString());
return words.toArray(new String[words.size()]);
}
public String reverse(String s) {
StringBuilder res=new StringBuilder();
for (int i = 0; i < s.length(); i++)
res.insert(0,s.charAt(i));
return res.toString();
}
不使用split,使用reverse
//7ms
public static String reverseWords(String s) {
StringBuilder res = new StringBuilder();
String[] s1 = s.split(" ");
for (int i = 0; i <s1.length ; i++) {
StringBuilder builder = new StringBuilder(s1[i]);
res.append(builder.reverse()+" ");
}
return new String(res).trim();
}
也可以使用双指针,并且不使用split
//5ms
final char[] cArr = s.toCharArray();
int from = -1;
int to = -1;
char tmpC = 0;
for (int i = 0; i < cArr.length; i++) {
if (from == -1) {
from = i;
} else if (' ' == cArr[i]) {
to = i - 1;
}
if (i == cArr.length - 1 && ' ' != cArr[i]) {
to = i;
}
if (to != -1 && from != -1) {
while (from < to) {
tmpC = cArr[from];
cArr[from] = cArr[to];
cArr[to] = tmpC;
from++;
to--;
}
from = -1;
to = -1;
}
}
return new String(cArr);
}