力扣题目
解题思路
java代码
力扣题目:
给你一个字符串 s
,请你反转字符串中 单词 的顺序。
单词 是由非空格字符组成的字符串。s
中使用至少一个空格将字符串中的 单词 分隔开。
返回 单词 顺序颠倒且 单词 之间用单个空格连接的结果字符串。
注意:输入字符串 s
中可能会存在前导空格、尾随空格或者单词间的多个空格。返回的结果字符串中,单词间应当仅用单个空格分隔,且不包含任何额外的空格。
示例 1:
输入:s = "the sky is blue
" 输出:"blue is sky the
"
示例 2:
输入:s = " hello world " 输出:"world hello" 解释:反转后的字符串中不能存在前导空格和尾随空格。
示例 3:
输入:s = "a good example" 输出:"example good a" 解释:如果两个单词间有多余的空格,反转后的字符串需要将单词间的空格减少到仅有一个。
解题思路:
在 reverseWords
方法中:
- 首先使用
split(" ")
方法按照空格将输入的字符串s
分割成单词数组split
。 - 然后创建一个
StringBuilder
对象sb
用于构建反转后的字符串。 - 通过一个从数组末尾到开头的循环,将非空的单词添加到
sb
中,并在每个单词后添加一个空格。 - 最后使用
trim
方法去除字符串末尾可能多余的空格,并返回结果。
在 main
方法中,创建了一个测试用的字符串 "the sky is blue"
,调用 reverseWords
方法对其进行处理,并将结果打印输出。
java代码:
package org.example.mouth7.today23;
public class Leetcode151 {
public static void main(String[] args) {
String s = "the sky is blue";
String s1 = reverseWords(s);
System.out.println(s1);
}
public static String reverseWords(String s) {
String[] split = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = split.length - 1; i >= 0; i--) {
if (!"".equals(split[i])) {
sb.append(split[i]).append(" ");
}
}
return sb.toString().trim();
}
}
更多详细内容同步到公众号,感谢大家的支持!
每天都会给刷算法的小伙伴推送明日一题,并且没有任何收费项