题解 | #单词倒排# 简单易行

单词倒排

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

import java.util.*;
import java.lang.*;

/**
难点:
    while(i>=0 && Character.isLetter(c)){
                i--;
                c = str.charAt(i);
            }
            res.append(str.substring(i+1,j+1)+" ");
    这样写会出现越界错误,因为当i=0时,i--会变成-1,str.charAt(-1)会报错。所以不如直接去掉c
 */
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        StringBuilder res = new StringBuilder();
        int n = str.length();
        int i = n - 1;
        int j = n - 1;

        while (i >= 0) {
            while (i >= 0 && Character.isLetter(str.charAt(i))) {
                i--;
            }
            res.append(str.substring(i + 1, j + 1) + " ");

            while (i >= 0 && !Character.isLetter(str.charAt(i))) {
                i--;
            }
            j = i;
        }
        System.out.println(res.toString().trim());
    }
}

全部评论

相关推荐

07-07 17:06
已编辑
深圳技术大学 golang
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-11 15:08
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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