题解 | #字符串反转#

字符串反转

https://www.nowcoder.com/practice/e45e078701ab4e4cb49393ae30f1bb04

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            //调用stringbuffer的翻转方法
            String a = in.nextLine();
            StringBuffer sb = new StringBuffer(a);            
            System.out.println(sb.reverse());
        }
    }
}

一、使用 StringBuilder 或 StringBuffer 的 reverse 方法

他们的本质都是调用了它们的父类 AbstractStringBuilder 的 reverse 方法实现的(需要JDK1.8)

	/**
     * 使用StringBuilder的reverse()方法将字符串反转
     */
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("ABCDE牛");
        System.out.println(sb.reverse());
    }

12345678

输出结果:

二、自己实现反转代码

	/**
     * 自己实现字符串反转
     */
    public static void main(String[] args) {
        String str = "ABCDE牛";
        //方式一  取出最后一个,然后一个一个复制给数组
        char[] chars = new char[str.length()];
        for (int i = str.length() - 1; i >= 0; i--) {
            chars[str.length() - 1 - i] = str.charAt(i);
        }
        System.out.println(chars);
        //方式二  截取出最后一个,然后一个一个输出
         for(int i = str .length() -1 ; i>= 0; i--){
            System.out.print(str.substring(i,i+1));
        }
    }
12345678910111213141516

输出结果:

三、使用递归方式

/**
     * 使用递归反转字符串
     */
    public static void main(String[] args) {
        String str = "ABCDE牛";
        System.out.println(stringReversalRecursion(str));
    }
    /**
     * 递归方法
     */
    public static String stringReversalRecursion(String str) {
        if (str == null || str.length() <= 1) {
            return str;
        }
        return stringReversalRecursion(str.substring(1)) + str.charAt(0);
    }

1234567891011121314151617

输出结果:

#字符串翻转#
全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 17:33
点赞 评论 收藏
分享
每晚夜里独自颤抖:这个在牛客不是老熟人了吗
点赞 评论 收藏
分享
nus22016021404:兄弟,你这个简历撕了丢了吧,就是一坨,去找几个项目,理解项目流程,看几遍就是你的了,看看八股就去干了,多看看牛客里别人发出来的简历,对着写,你这写的啥啊,纯一坨
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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