任务六
leetcode557:反转字符串中的单词 III
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例 1:
输入: “Let’s take LeetCode contest”
输出: “s’teL ekat edoCteeL tsetnoc”
注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
class Solution {
public String reverseWords(String s) {
StringBuilder res = new StringBuilder();
String[] split = s.split(" ");
for (int i = 0; i < split.length; i++) {
String str = split[i];
char[] chars = str.toCharArray();
int front = 0;
int tail = chars.length - 1;
for (int j = 0; j < chars.length; j++) {
if(front > tail){
break;
}
char temp = chars[front];
chars[front] = chars[tail];
chars[tail] = temp;
front++;
tail--;
}
res.append(new String(chars) + (i == split.length-1 ? "" : " "));
}
return res.toString();
}
}
现在还处于基本用法字符串拼接和分割等,都需要百度的情况,速度太慢了。