例如输入:I love programming
输出:I evol gnimmargorp
算法思路就是:根据空格提取每一个单词,存放在一个buffer里进行翻转处理,再添加到新的字符串。最后新的字符串就完成整个方法过程。
public class ReserveString {
public String reserve(String sentence){
String backS = new String();
StringBuffer temp = new StringBuffer();
int i=0;
while (i<sentence.length()-1 && sentence.charAt(i)!=' '){
temp.append(sentence.charAt(i));
i++;
if (i==sentence.length()-1 || sentence.charAt(i)==' '){
if (i==sentence.length()-1) {temp.append(sentence.charAt(i));}
int ii=temp.length()-1;
int jj=0;
while (ii-jj>=0){
char Sii=temp.charAt(ii);
char Sjj=temp.charAt(jj);
temp.setCharAt(ii,Sjj);
temp.setCharAt(jj,Sii);
ii--;jj++;
}//得到单个单词并反转
i++; //跳过空格
backS=backS+temp+" "; //添加翻转后单词和空格
temp = new StringBuffer(); //重置temp存放单个单词
}
}
return backS;
}
public static void main(String[] args) {
ReserveString reserveString = new ReserveString();
System.out.println(reserveString.reserve("I love programming rly"));
}
}