Java写题解的第1天:句子逆序
题目限定输入只有字母和空格,因此只需要从左往右遍历,判断是否有空格字符即可;
如果不限定字母和空格,比如还有数字或者其他字符作为分割符,只要使用Character.isLetter(c)
判断即可;
由于需要倒序输出,每个单词之间只能有一个空格,且最后不能有空格,因此使用栈来进行存储和输出;
import java.io.*; import java.util.Stack; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); char[] cs = br.readLine().toCharArray(); br.close(); Stack<String> stack = new Stack<>(); int left = 0, right = 0; while (left < cs.length) { if (cs[left] == ' ') { left++; } else { right = left; StringBuilder sb = new StringBuilder(); while (right < cs.length && cs[right] != ' ') { sb.append(cs[right]); right++; } stack.push(sb.toString()); stack.push(" "); left = right + 1; } } stack.pop(); while (!stack.isEmpty()) { System.out.print(stack.pop()); } } }