题解 | #单词倒排#

单词倒排

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

方法一:

使用正则表达式匹配非字母字符进行字符串分割,然后逆序输出。

public class DanCiNiXu2 {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String s = scanner.nextLine();
            String[] strings = s.split("[^a-zA-Z]");
            //逆序输出,注意空白。非空白进行输出,单词与单词之间用空格拼接
            StringBuilder builder = new StringBuilder();
            for (int i = strings.length-1; i >= 0; i--){
                if (!strings[i].trim().isEmpty()){ //非空进行添加
                    builder.append(strings[i]);
                    builder.append(" "); //使用空格隔开
                }
            }
            System.out.println(builder.toString());
        }
    }
}

方法二:

将非字母的字符替换成空格,然后根据空格进行split,逆序输出分割后的字符串数组即可。

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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