题解 | #句子逆序#
句子逆序
http://www.nowcoder.com/practice/48b3cb4e3c694d9da5526e6255bb73c3
import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); String str = input.nextLine(); char[] chars = str.toCharArray(); int index = 0; swap(chars, 0, chars.length - 1); int start = 0; int end = 0; for (int i = 0; i < chars.length; i++) { if (i == 0 || chars[i - 1] == ' ') { start = i; } if (i == chars.length - 1 || chars[i + 1] == ' ') { end = i; } if (end > start) { swap(chars, start, end); start = 0; end = 0; } } System.out.println(String.valueOf(chars)); }
public static void swap(char[] chars, int start, int end) {
while (start < end) {
char temp = chars[start];
chars[start] = chars[end];
chars[end] = temp;
start++;
end--;
}
}
}