单词倒序 华为OD真题 100


public class Main{
 
    public static void main(String[] args) {
 
        Scanner sc = new Scanner(System.in);
 
        String string = sc.nextLine();
 
        String res = "";
        String temp = "";   //用来拼接字符的临时容器
        for(int i=0; i<string.length(); i++){
            char c = string.charAt(i);
            if(Character.isLetter(c)){      //判断是否是字母
                temp += c;
            }else if(c == ' '){
                res += reverse(temp) + " ";     //遇到空格,对temp进行反转,需要加上空格
                temp = "";  //需要对temp置空
            }else {
                if(temp !=  ""){
                    res += reverse(temp);   //如果temp不为空则需要反转后拼接
                    temp = "";      //对temp进行置空
                }
                res += c;       //标点符号直接进行拼接
            }
            if(i == string.length()-1 && temp != ""){
                res += reverse(temp);   //如果最后一个字符是字母
            }
        }
 
        System.out.println(res);
    }
 
    /**
     * 反转字符串中的字符
     * @param str
     * @return
     */
    public static String reverse(String str){
 
        String res =  "";
        for(int i = str.length()-1; i>=0; i--){
            res += str.charAt(i);
        }
 
        return res;
 
    }
 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值