题解 | #单词倒排#

单词倒排

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNextLine()) {
        String firstLine = scanner.nextLine();
            List<String> strs = new ArrayList<>();
            StringBuilder sb = new StringBuilder();
            for(int i = 0; i < firstLine.length(); i ++)
            {

                if((firstLine.charAt(i) >= 'a' &&
                firstLine.charAt(i) <= 'z') ||
                        (firstLine.charAt(i) >= 'A' &&
                                firstLine.charAt(i) <= 'Z'))
                {
                    sb.append(firstLine.charAt(i));
                }else{
                    if(sb.length() >= 1)
                    {
                        strs.add(sb.toString());
                        sb.delete(0,sb.length());
                    }
                }
            }
            /**
             * 请注意把最后一个字符串添加到strs里
             */
            if(sb.length() >= 1)
            {
                strs.add(sb.toString());
                sb.delete(0,sb.length());
            }
            /**
             * 请注意题目中的倒排,是从尾到头这样输出,并不是把这些字符串按照sort排序之后输出
             */
            for(int i = strs.size() - 1; i >= 0; i --)
            {
                System.out.print(strs.get(i) + " ");
            }
        }
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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