题目:将一句话的单词进行倒置,标点不倒置。
解题思路:写一个数组逆置方法,先将整个字符串数组逆置,再将每个单词逆置即可。
代码:
import java.util.*;
public class Main{
//逆置方法
public static void reverse (char[] arrry,int start,int lost) {
while(start < lost) {
char tmp = arrry[start];
arrry[start] = arrry[lost];
arrry[lost] = tmp;
start++;
lost--;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.nextLine();
char[] ch = s.toCharArray();
int len = ch.length;
//整体进行逆置
reverse(ch,0,len-1);
int i = 0;
//单词逆置
while(i < len) {
int j = i;
while(j < len&&ch[j] != ' ') {
j++;
}
if(i < len){
reverse(ch,i,j-1);
i = j+1;
}else {
reverse(ch,i,j-1);
i = j;
}
}
String str = new String(ch);
System.out.println(str);
}
}