题目:Reverse Words in a String
难度:medium
问题描述:
Given an input string, reverse the string word by word.
Example:
Input: "the sky is blue
", Output: "blue is sky the
".
结题思路:遍历字符串,找到每个单词,逆序拼接。
代码如下:
public static String reverseWords(String s) {
char[] ch = s.toCharArray();
int index = 0;
LinkedList<String> list = new LinkedList<>();
while(index<ch.length){
//剔除空格
while(index<ch.length && ch[index]==' ' ){
index++;
}
StringBuilder str = new StringBuilder();
while(index<ch.length && ch[index]!=' '){
str.append(ch[index++]);
}
if(str.length()>0){
list.add(str.toString());
}
}
Iterator<String> ite = list.descendingIterator();
StringBuilder str = new StringBuilder();
while(ite.hasNext()){
str.append(ite.next());
if(ite.hasNext()) str.append(" ");
}
return str.toString();
}