题解-翻转单词顺序列
翻转单词顺序列
http://www.nowcoder.com/questionTerminal/3194a4f4cf814f63919d0790578d51f3
直接以单词为单位进行翻转就可以了,不知道为什么都是清一色的翻转两次..
非法判断比较坑,要注意:
- 遇到" "要用trim()去除多余的空格,才能用equals判断
- 返回str,不要直接返回""
public String ReverseSentence(String str) { if(str == null || str.length() == 0) return str; str = str.trim(); String[] arr = str.split(" "); int length = arr.length; int low = 0, high = length - 1; while(low < high){ String tmp = arr[low]; arr[low] = arr[high]; arr[high] = tmp; low++; high--; } StringBuilder s = new StringBuilder(); for(int i = 0; i < length - 1; i++){ s.append(arr[i] + " "); } s.append(arr[length - 1]); return s.toString(); }