Leetcode链接:557. 反转字符串中的单词 III
题目描述
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例:
输入:“Let’s take LeetCode contest”
输出:“s’teL ekat edoCteeL tsetnoc”
提示:
在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
方法一:原数组修改
class Solution {
//1.修改原数组
public String reverseWords(String s) {
int n = s.length();
if(n == 0 || n == 1) return s;
char[] chars = s.toCharArray();
int i = 0;
while(i < n){
int start = i;
//找空格
while(i < n && chars[i] != ' '){
i++;
}
//字符串反转
int left = start;
int right = i - 1;
while(left < right){
swap(chars, left, right);
left ++;
right --;
}
//跳过空格
while(i < n && chars[i] == ' '){
i++;
}
}
return String.valueOf(chars);
}
public void swap(char[] chars, int i, int j){
char tmp = chars[i];
chars[i] = chars[j];
chars[j] = tmp;
}
}
方法二:切割字符串(自己解法)
class Solution {
public String reverseWords(String s) {
int len = s.length();
if(len == 0) return s;
String[] split = s.split(" ");
String result = reverse(split[0]);
for(int i = 1; i < split.length; i ++){
result = result + ' ' + reverse(split[i]);
}
return result;
}
public String reverse(String subStr){
char[] chars = subStr.toCharArray();
int i = 0;
int j = chars.length - 1;
while(i < j){
char tmp = chars[i];
chars[i] = chars[j];
chars[j] = tmp;
i++;
j--;
}
return String.valueOf(chars);
}
}