Given an input string, reverse the string word by word.
public class Solution {
public String reverseWords(String s) {
if(s == null || s.trim().length() == 0)
return s.trim();
String[] temp =helper(s).split(" ");//整体翻转不用trim
String sentence = "";
for(String t : temp){
if(t.trim().equals(""))
continue;
sentence += helper(t) + " ";
}
return sentence.trim();
}
//不用去除空格
private String helper(String s){
char[] cs = s.trim().toCharArray();
int ss = 0, e = cs.length - 1;
while(ss < e){
char temp = cs[ss];
cs[ss] = cs[e];
cs[e] = temp;
ss ++;
e --;
}
return new String(cs);
}
}
class Solution:
def reverseWords(self, s: str) -> str:
s = s[::-1]
s = s.strip().split()
return ' '.join([''.join(i.strip()[::-1]) for i in s])