题目描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一翻转这些单词顺序可不在行,你能帮助他么?
解题思路
很简单的题,也没啥好说的,注意一下测试用例为全是空格的情况:” ”
trim() : 去除字符串首尾空格
split() : 对字符串按照所传参数进行分割
参考代码
Java
public class Solution {
public String ReverseSentence(String str) {
// 边界条件
if(str.trim().length() == 0)
return str;
// 字符串切分
String[] temp = str.split(" ");
String res = "";
// 逆序遍历
for(int i = temp.length - 1; i >= 0; i--){
res += temp[i];
if(i != 0)
res += " ";
}
return res;
}
}
Python
# -*- coding:utf-8 -*-
class Solution:
def ReverseSentence(self, s):
# write code here
if len(s.strip()) == 0: return s
s_list = s.strip().split()
res = ""
for i in range(len(s_list) - 1,-1,-1):
res += s_list[i]
if i != 0:
res += " "
return res
个人订阅号
网友评论