https://leetcode.com/problems/reverse-words-in-a-string/
题目描述
Given an input string, reverse the string word by word.
Example 1:
Input: “the sky is blue”
Output: “blue is sky the”
解题思路
用split()将string分解成list, 然后反转list再组合.
代码
Python
class Solution:
def reverseWords(self, s: str) -> str:
slist = s.strip().split()
slist = slist[::-1]
return " ".join(slist)
Java
public class Solution {
public String reverseWords(String s) {
String [] words = s.split(" ");
StringBuilder sb = new StringBuilder();
int end = words.length - 1;
for(int i = 0; i<= end; i++){
if(!words[i].isEmpty()) {
sb.insert(0, words[i]);
if(i < end) sb.insert(0, " ");
}
}
return sb.toString();
}
}