题目链接
给你一个字符串 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"
解释:如果两个单词间有多余的空格,颠倒后的字符串需要将单词间的空格减少到仅有一个。
提示:
- 1 <= s.length <= 104
- s 包含英文大小写字母、数字和空格 ‘ ‘
-
思路
先去掉头尾和中间多余的字符串,再从后往前将每一个单词填入字符串中
class Solution { public static String reverseWords(String s) { StringBuffer stringBuffer = cutSpace(s); StringBuffer result = new StringBuffer(); int j = stringBuffer.length() - 1; for (int i = stringBuffer.length() - 1; i >= 0; i--) { // 找到每个单词的开头 // 限制j>0是为了以一个字母为单词开头时,控制j不会小于0 while (stringBuffer.charAt(j) != ' ' && j > 0) { j--; } // 向结果添加单词,注意是前闭后开的 if (j == 0) { // 第一个单词的情况 result.append(stringBuffer.subSequence(0, i + 1)); break; } else if (stringBuffer.charAt(j) == ' ') { // 其它单词的情况 result.append(stringBuffer.subSequence(j + 1, i + 1)); result.append(' '); i = j; j--; } } return result.toString(); } /** * 去除首位的字符串 */ private static StringBuffer cutSpace(String s) { int i = 0; int j = s.length() - 1; // 开始的空格 while (i < s.length()) { if (s.charAt(i) == ' ') { i++; continue; } if (s.charAt(i) != ' ') { break; } } // 结尾的空格 while (j >= 0) { if (s.charAt(j) == ' ') { j--; continue; } if (s.charAt(j) != ' ') { break; } } StringBuffer afterCut = new StringBuffer(); while (i <= j) { if (s.charAt(i) != ' ') { afterCut.append(s.charAt(i)); } else if (s.charAt(i - 1) != ' ') { afterCut.append(s.charAt(i)); } i++; } return afterCut; } }
