题解 | #HJ031 单词倒排#

单词倒排

http://www.nowcoder.com/practice/81544a4989df4109b33c2d65037c5836

import java.util.Scanner;

/**
 * HJ31 单词倒排
 */
public class HJ031 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String str = sc.nextLine();
            String res = reverse(str);
            System.out.println(res);
        }
        sc.close();
    }

    private static String reverse(String str) {
        // 匹配非字母的字符进行分割
        String[] words = str.split("[^A-Za-z]");
        StringBuilder result = new StringBuilder();
        // 逆序添加分割完的单词
        for (int i = words.length - 1; i >= 0; i--) {
            result.append(words[i]).append(" ");
        }
        return result.toString().trim();
    }

}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务