网站开发初级技术人员,免费ppt下载软件,微平台推广是什么,佛山网站制作网站设计给定一个字符串#xff0c;逐个翻转字符串中的每个单词。 示例 1#xff1a;
输入: the sky is blue 输出: blue is sky the 示例 2#xff1a;
输入: hello world! 输出: world! hello 解释: 输入字符串可以在前面或…给定一个字符串逐个翻转字符串中的每个单词。 示例 1
输入: the sky is blue 输出: blue is sky the 示例 2
输入: hello world! 输出: world! hello 解释: 输入字符串可以在前面或者后面包含多余的空格但是反转后的字符不能包括。 示例 3
输入: a good example 输出: example good a 解释: 如果两个单词间有多余的空格将反转后单词间的空格减少到只含一个。
说明
无空格字符构成一个单词。 输入字符串可以在前面或者后面包含多余的空格但是反转后的字符不能包括。 如果两个单词间有多余的空格将反转后单词间的空格减少到只含一个。
思路以空格为界限把字符串拆成字符串数组
数组中会有以下几种情况
1. 出现单词而无空格-将单词连接到结果字符串中
2. 出现单词及空格-去掉空格再将单词连接到结果字符串中
3. 只有空格-去掉空格之后它为空不用管了
提交的代码
class Solution { public String reverseWords(String s) { String emptyStr ; final String[] s1 s.trim().split(emptyStr); StringBuilder sbnew StringBuilder(); for (int i s1.length - 1; i 0; i--) { String strs1[i]; while (str.contains(emptyStr)){ strstr.replaceAll(emptyStr,); } if (.equals(str)){ continue; } sb.append(str); if (i!0){ sb.append(emptyStr); } } return sb.toString(); }
}