【题目描述】

给你一个字符串 ​​s​​ ,请你反转字符串中 单词 的顺序。

单词 是由非空格字符组成的字符串。​​s​​ 中使用至少一个空格将字符串中的 单词 分隔开。

返回 单词 顺序颠倒且 单词 之间用单个空格连接的结果字符串。

注意:输入字符串 ​​s​​中可能会存在前导空格、尾随空格或者单词间的多个空格。返回的结果字符串中,单词间应当仅用单个空格分隔,且不包含任何额外的空格。

​https://leetcode.cn/problems/reverse-words-in-a-string/​


【示例】

【LeeCode】151. 反转字符串中的单词_java


【代码】admin

思路: 基于空格分隔(正则), 然后反向输出即可

package com.company;
import java.util.*;

// 2022-02-18
class Solution {
public String reverseWords(String s) {
String str = s.trim();
String[] split = str.split("\\s+");
StringBuilder sb = new StringBuilder();

for (int i = split.length - 1; i >= 0; i--){
sb.append(split[i]).append(" ");
}
// System.out.println(sb.toString().trim());
return sb.toString().trim();
}
}
public class Test {
public static void main(String[] args) {
new Solution().reverseWords("the sky is blue"); // 输出:"blue is sky the"
new Solution().reverseWords( " hello world "); // 输出:"world hello"
new Solution().reverseWords( "a good example"); // 输出:"example good a"
}
}


【代码】​​LeeCode--内置函数​

【LeeCode】151. 反转字符串中的单词_字符串_02

package com.company;
import java.util.*;

// 2022-02-18
class Solution {
public String reverseWords(String s) {
s = s.trim();
List<String> strings = Arrays.asList(s.split("\\s+"));
Collections.reverse(strings);
System.out.println(String.join(" ", strings));
return String.join(" ", strings);
}
}
public class Test {
public static void main(String[] args) {
new Solution().reverseWords("the sky is blue"); // 输出:"blue is sky the"
new Solution().reverseWords( " hello world "); // 输出:"world hello"
new Solution().reverseWords( "a good example"); // 输出:"example good a"
}
}


【代码】​​LeeCode--双端队列​

【LeeCode】151. 反转字符串中的单词_java_03

package com.company;
import java.util.*;

// 2022-02-18
class Solution {
public String reverseWords(String s) {

int left = 0;
int right = s.length() - 1;
// 去掉开头字符
while (left <= right && s.charAt(left) == ' '){
++left;
}
// 去掉结尾字符
while (left <= right && s.charAt(right) == ' '){
--right;
}

Deque<String> stack = new ArrayDeque<>();
StringBuilder sb = new StringBuilder();
while (left < right){
char c = s.charAt(left);
if ((sb.length() != 0) && (c == ' ')){
stack.offerFirst(sb.toString());
sb.setLength(0);
}else if (c != ' '){
sb.append(c);
}
left++;
}
stack.offerLast(sb.toString());
return String.join(" ", stack);
}
}
public class Test {
public static void main(String[] args) {
new Solution().reverseWords("the sky is blue"); // 输出:"blue is sky the"
new Solution().reverseWords( " hello world "); // 输出:"world hello"
new Solution().reverseWords( "a good example"); // 输出:"example good a"
}
}