题解 | #单词倒排#

单词倒排

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

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        char[] chars = str.toCharArray();
        String endStr = "";// 最终的输出结果
        StringBuilder tmp = new StringBuilder();// 临时变量,表示当前处理的单词
        for(int i = chars.length-1 ; i >= 0 ; i--){
            char c = chars[i];
            if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')){
                tmp.append(c+"");
            }else{
                // 将tmp进行反转
                endStr += tmp.reverse().toString();
                tmp = new StringBuilder();
                // 保证单词之间只有一个空格
                if(!endStr.endsWith(" ")){
                    endStr += " ";
                }
            }
        }
        // 拼上最后一个单词
        if(endStr.endsWith(" ")){
            endStr += tmp.reverse().toString();
        }
        System.out.print(endStr);
    }
}

全部评论

相关推荐

notbeentak...:真的nc,算毕业6月份,要给这种b公司打半年多白工😅
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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