151.Reverse Words in a String
Given an input string, reverse the string word by word.
For example,
Given s = “the sky is blue
“,
return “blue is sky the
“.
思路:给定一个字符串,逆向排序后输出。可以转换成字符串数组排序后输出,注意的是String.split()函数,如果给定的字符串中有多个空格,如:
" a b "
如果单单使用String.split(” “)会返回中间的空格,所以需要使用String.split(” +”);
代码如下:
/**
* Created by Poldi on 2017/7/7.
*/
public class ReverseWordsInAString {
public String reverseWords(String s) {
String[] strings = s.trim().split(" +");
String result = "";
for (int i=0;i<strings.length/2;i++){
String temp = strings[i];
strings[i] = strings[strings.length-1-i];
strings[strings.length-1-i] = temp;
}
result = String.join(" ",strings);
return result;
}
public static void main(String[] args) {
ReverseWordsInAString reverseWordsInAString = new ReverseWordsInAString();
System.out.println(reverseWordsInAString.reverseWords(" a b "));
}
}
这边我是直接运用了循环遍历,前后对应赋值的方法,还有更简便的方法:
public String reverseWords(String s) {
String[] strings = s.trim().split(" +");
Collections.reverse(Arrays.asList(strings));
String result = String.join(" ",strings);
return result;
}
直接运用了Collections的reverse方法
@SuppressWarnings({"rawtypes", "unchecked"})
public static void reverse(List<?> list) {
int size = list.size();
if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)
swap(list, i, j);
} else {
// instead of using a raw type here, it's possible to capture
// the wildcard but it will require a call to a supplementary
// private method
ListIterator fwd = list.listIterator();
ListIterator rev = list.listIterator(size);
for (int i=0, mid=list.size()>>1; i<mid; i++) {
Object tmp = fwd.next();
fwd.set(rev.previous());
rev.set(tmp);
}
}
}
从reverse的源码中可以看出逆序的原理是相同的