题解 | #翻转单词序列#
翻转单词序列
http://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3
1. python 解法(归功于python强大的切片功能以及弱类型引用,写出的代码真的很简洁)
# -*- coding:utf-8 -*- class Solution: def ReverseSentence(self, s): # write code here ls = [ss for ss in s.split(' ')] return ' '.join(ls[::-1])
2. java解法(取了个巧,用到了Collection类的序列翻转函数,此处就体现了java强大的api生态,啥都有)
import java.util.*; public class Solution { public String ReverseSentence(String str) { String[] ss = str.split(" "); List<String> strsToList1= Arrays.asList(ss); Collections.reverse(strsToList1); String ss1 = String.join(" ", strsToList1); return ss1; } }
package main /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param str string字符串 * @return string字符串 */ import "strings" func ReverseSentence( str string ) string { // write code here ss := strings.Split(str, " ") for i:=0;i<len(ss)/2;i++{ tmp := ss[len(ss)-1-i] ss[len(ss)-1-i] = ss[i] ss[i] = tmp } return strings.Join(ss, " ") }