59 lines
2.1 KiB
Java
59 lines
2.1 KiB
Java
package array;
|
||
/**
|
||
* 题目: 151. 反转字符串中的单词 (reverseWords)
|
||
* 描述:给你一个字符串 s ,请你反转字符串中 单词 的顺序。
|
||
* 单词 是由非空格字符组成的字符串。s 中使用至少一个空格将字符串中的 单词 分隔开。
|
||
* 返回 单词 顺序颠倒且 单词 之间用单个空格连接的结果字符串。
|
||
* 注意:输入字符串 s中可能会存在前导空格、尾随空格或者单词间的多个空格。返回的结果字符串中,单词间应当仅用单个空格分隔,且不包含任何额外的空格。
|
||
*
|
||
* 示例 1:
|
||
输入:s = "the sky is blue"
|
||
输出:"blue is sky the"
|
||
|
||
* 链接:https://leetcode.cn/problems/reverse-words-in-a-string/
|
||
*/
|
||
public class ReverseWords {
|
||
public String reverseWords(String s) {
|
||
StringBuilder result = new StringBuilder();
|
||
int endIndex = s.length(); // endIndex指向字符串的末尾
|
||
int startIndex;
|
||
|
||
// 遍历字符串,按单词逆序拼接
|
||
while (endIndex > 0) {
|
||
// 找到当前单词的结尾,跳过空格
|
||
while (endIndex > 0 && s.charAt(endIndex - 1) == ' ') {
|
||
endIndex--;
|
||
}
|
||
|
||
// 如果endIndex已经指向开头,说明没有更多单词了
|
||
if (endIndex == 0) {
|
||
break;
|
||
}
|
||
|
||
// 找到当前单词的开始位置
|
||
startIndex = endIndex;
|
||
while (startIndex > 0 && s.charAt(startIndex - 1) != ' ') {
|
||
startIndex--;
|
||
}
|
||
|
||
// 将单词添加到StringBuilder
|
||
if (result.length() > 0) {
|
||
result.append(" "); // 添加单个空格
|
||
}
|
||
result.append(s.substring(startIndex, endIndex));
|
||
|
||
// 更新endIndex,准备处理下一个单词
|
||
endIndex = startIndex;
|
||
}
|
||
|
||
return result.toString();
|
||
}
|
||
|
||
public static void main(String[] args) {
|
||
ReverseWords rw = new ReverseWords();
|
||
String s = " the sky is blue ";
|
||
System.out.println(rw.reverseWords(s)); // 输出: "blue is sky the"
|
||
}
|
||
}
|
||
|