解题思路:现将整个字符串将"I am Student!"逆置,得到字符串"!tnedutS ma I",在逆置每一个单词,得到字符串"Student! am I";所以要写一个方法逆置数组,一个方法来判断单词,调用逆置数组的方法实现单词的逆置。
package com.tulun.suanfa;
/**
* 将字符串"I am Student!"转换为"Student! am I"
* @author lzq
*
*/
public class ZiFuChuan {
/**
* 逆置数组
* @param ch
* @param left
* @param right
*/
public static void reverse(char[] ch,int left,int right) {
char tmp = '\u0000';
while(left < right) {
tmp = ch[left];
ch[left] = ch[right];
ch[right] = tmp;
left++;
right--;
}
}
/**
* 先逆置整个数组,然后找到每个单词,逆置每个单词
* @param str
* @return
*/
public static String inversion(String str) {
char ch[] = str.toCharArray();
int left = 0;
int right = str.length()-1;
int cur = 0;
reverse(ch,left,right);//逆置整个数组
while(cur != str.length()-1) {
int start = cur;
while(ch[cur] != ' ') {//找到每个单词
cur++;
}
reverse(ch,start,cur-1);//逆置每个单词
if(ch[cur] == ' ') {
cur++;
}
}
return String.copyValueOf(ch);
}
public static void main(String[] args) {
String str = "I am Student!";
System.out.println(inversion(str));
}
}
运行结果:
Student! am I