思路:切割+反向拼接(Java)
翻转单词顺序列
http://www.nowcoder.com/questionTerminal/3194a4f4cf814f63919d0790578d51f3
1、借助库函数split实现
public static String ReverseSentence(String str) { if(str == null || str.length() ==0)return str; String[] strings = str.split(" "); if(strings.length == 0)return str; StringBuilder res = new StringBuilder(); for(int i = strings.length - 1;i>=0;i--){ res.append(strings[i]).append(" "); } return res.toString().trim(); }
2、自己实现库函数split功能
public static String ReverseSentence(String str) { if(str == null || str.length() ==0 ||"".equals(str.trim()))return str; ArrayList<String> list = new ArrayList<>(); StringBuilder res = new StringBuilder(); StringBuilder sb = new StringBuilder(); for(int i = 0;i<str.length();i++){ if(str.charAt(i) == ' '||(i == str.length() - 1)){ list.add(sb.append(str.charAt(i)==' '?"":str.charAt(i)).toString()); sb = new StringBuilder(""); }else{ sb.append(str.charAt(i)); } } String[] result = new String[list.size()]; result = (String[])list.subList(0, list.size()).toArray(result); for(int i = result.length - 1;i>=0;i--){ res.append(result[i]).append(" "); } return res.toString().trim(); }