/**
* 单词翻转。输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变,句子中单词以空格符隔开。为简单起见,
* 标点符号和普通字母一样处理。例如,输入“I am a student.”,则输出“student. a am I”。
* @author Administrator
*
*算法分析:(1)先将整个句子翻转,.tneduts a ma I
* (2)再按照空格将每个单词翻转
*/
public class RotateSentence {
public static void ReverseString(char[] s,int from, int to){
while(from<to){
char t=s[from];
s[from++]=s[to];
s[to--]=t;
}
}
public static void ReverseSentence(String str){
char[] s=str.toCharArray();
int from=0;
//将整个句子翻转
ReverseString(s, 0, s.length-1);
for(int i=0;i<s.length;i++){
if(Character.isWhitespace(s[i])){
ReverseString(s, from, i-1);
from+=i+1;
continue;
}
}
System.out.println(s);
}
public static void main(String[] args) {
String str="I am a student.";
ReverseSentence(str);
}
}
单词翻转
最新推荐文章于 2023-12-17 18:55:00 发布