题目
输入一个英文句子, 翻转句子中单词的顺序, 但单词内字符的顺序不变. 为简单起见, 标点符号和普通字母一样处理. 例如输入字符串"Iam a student.", 则输出"student. a am I"。
解题思路
(1)先翻转单词,再翻转顺序列(不借助额外的空间)
源代码
public class ReverseSentence {
public static String reverseSentence(String str) {
int n = str.length();
char[] chars = str.toCharArray();
int i = 0, j = 0;
while (j <= n) {
if (j == n || chars[j] == ' ') {//转换单个单词
reverse(chars, i, j - 1);
i = j + 1;
}
j++;
}
reverse(chars, 0, n - 1);//翻转整个字符数组
return new String(chars);
}
private static void reverse(char[] chars, int i, int j) {
while (i < j)
swap(chars, i++, j--);
}
private static void swap(char[] chars, int i, int j) {//交换字符串数组第i和第j位置的元素
char c = chars[i];
chars[i] = chars[j];
chars[j] = c;
}
public static void main(String[] args) {
System.out.println(reverseSentence("I am a student!"));
}
}
(2)将字符串按空格切割成字符串数组,以数组长度的一半为原点,将距离原点相等的下标数组元素进行交换,最后遍历输出数组元素即可。
源代码
public class ReverseSentence {
public static String reverseSentence1(String str) {
String[] strings = str.split(" ");
String result = "";
int length = strings.length;
for (int i = 0; i < strings.length / 2; i++) {
String temp = strings[i];
strings[i] = strings[length - i - 1];
strings[length - i - 1] = temp;
}
for (int i = 0; i < length; i++) {
result += strings[i];
if (i != length - 1)
result += " ";
}
return result;
}
public static void main(String[] args) {
System.out.println(reverseSentence1("I am a student!"));
}
}
(2)借用辅助空间栈实现,Stack
源代码
package Arithmetic;
import java.util.Scanner;
import java.util.Stack;
public class WordReverse {
private static Stack<String> stack = new Stack<>();
public static String wordReverse(String string) {
stack.clear();
String[] strings = string.split(" ");
String result = "";
for (int i = 0; i < strings.length; i++) {
if (!"".equals(strings[i])){
stack.push(strings[i]);
}
}
int size = stack.size();
for (int j = 0; j < size; j++) {
result += stack.pop();
if (j < size - 1)
result += " ";
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
System.out.println(wordReverse(s));
}
}