/*
" ab c "转换成:"c ab"
输入的字串可以有leading space和tailing space,输出字串不可有,中间的连续空格转成单一空格
我的解法:
public String reverseWords(String s) {
String[] s1=s.split(" ");
ArrayList<String> list=new ArrayList<String>();
for (String string : s1) {
if(!string.equals(""))//这里千万不可以写成" "
list.add(string);
}
for (String string : list) {
System.out.println(string);
}
String reString="";
if(list.size()==0)
return "";
for (int i = list.size()-1; i>0; i--) {
reString+=list.get(i)+" ";
}
reString+=list.get(0);
return reString;
}
*/
************************************************************
StringBuilder reversed = new StringBuilder();
int j = s.length();//设定两个指针
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == ‘ ‘) {
j = i;//如果是s的初始连续空格,那么只会执行这段,不会走到append语句
} else if (i == 0 || s.charAt(i - 1) == ‘ ‘) {
if (reversed.length() != 0) {//当reversed的长度为0,不要添加‘ ’,因为是s末尾的连续空格,不加入
reversed.append(‘ ‘);
}
reversed.append(s.substring(i, j));
}
}
return reversed.toString();