class Solution {
public String reverseWords(String s) {
String word = "";
String res = "";
boolean first_word = true;
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(c == ' '){
if(word != ""){
if(!first_word){
word = word + " ";
}
res = word + res;
first_word = false;
}
word = "";
}
else
word += c;
}
if(word != ""){
if(!first_word)
word = word + " ";
res = word + res;
}
return res;
}
}
看题解
java复制代码
class Solution {
public String reverseWords(String s) {
// 除去开头和末尾的空白字符
s = s.trim();
// 正则匹配连续的空白字符作为分隔符分割
List<String> wordList = Arrays.asList(s.split("\\s+"));
Collections.reverse(wordList);
return String.join(" ", wordList);
}
}
作者:力扣官方题解
链接:https://leetcode.cn/problems/reverse-words-in-a-string/solutions/194450/fan-zhuan-zi-fu-chuan-li-de-dan-ci-by-leetcode-sol/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。