每日一题-Day28-反转字符串中的单词
题目
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序
示例:
输入:"Let's take LeetCode contest"
输出:"s'teL ekat edoCteeL tsetnoc"
解题思路
双指针:通过双指针和数组的概念来进行解答,指针i为字符串的索引,指针j为单个单词的索引,由单个单词的起始下标start来进行赋值,通过减去逐渐增大的索引j来实现单个单词的反转
class Solution {
public String reverseWords(String s) {
StringBuffer temp = new StringBuffer();
int i = 0;
while (i < s.length()) {
int start = i;
while (i < s.length() && s.charAt(i) != ' ') {
i++;
}
for (int j = start; j < i; j++) {
temp.append(s.charAt(start + i - j - 1));
}
while (i < s.length() && s.charAt(i) == ' ') {
temp.append(' ');
i++;
}
}
return temp.toString();
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/