• 图解算法——反转字符串


    1、题目描述

    接受一个只包含小写字母的字符串,然后输出该字符串反转后的字符串。(字符串长度不超过1000)。

    题目来源:
    https://www.nowcoder.com/practice/e45e078701ab4e4cb49393ae30f1bb04?tpId=37&tags=&title=&difficulty=0&judgeStatus=0&rp=1

    2、示例

    输入描述:输入一行,为一个只包含小写字母的字符串。

    输出描述:输出该字符串反转后的字符串。

    示例1:

    输入:abcd

    输出:dcba

    3、思路

    有了前车之鉴,上篇文章提到的反转整数的题目,很快会想到用stringBuffer的 reverse()反转函数。

    代码如下:

    import java.util.*;
    
    public class Main{
        public static void main(String[] args){
            Scanner sc  = new Scanner(System.in);
            while(sc.hasNextLine()){
                StringBuffer sb = new StringBuffer(sc.nextLine());
                sb.reverse();
                System.out.println(sb);
            }
        }
    }

    提交结果:

     还不错,击败了一半的人。但是呢?你想啊,面试官给你出这个题目,能让你用一个函数就解决掉嘛?

    所以,这个题目的意思,肯定是让你自己实现reverse() 函数的原理。

    so.......

    思路2:

    将输入的字符串转换成字符数组,然后逆序输出。

    代码如下:

    import java.util.*;
    
    public class Main{
        public static void main(String[] args){
            Scanner sc  = new Scanner(System.in);
            while(sc.hasNextLine()){
                String str = sc.nextLine();
                char[] chs = str.toCharArray();
                for(int i = str.length()-1; i>=0;i--){
                    System.out.print(chs[i]);
                }
            }
        }
    }

    看看提交结果如何:

     还不如思路一。因为自己又设定了一个char[] 数组来存放转换的字符串,所以内存空间又增大了。

    所以啊,还是根据上篇经验,只有序列化输入输出才会可能提高速度。

    思路3:

    import java.io.*;
    public class Main{
        public static void main(String[] args) throws IOException{
            InputStream in  = System.in;
            int len;
            byte[] b = new byte[1024];
            while((len = in.read(b)) > 0){
                String str = new String(b,0,len-1);
                char [] chars = str.toCharArray();
                char [] charsFb = new char[chars.length];
                for(int i = 0;i<chars.length;i++){
                    charsFb[i] = chars[chars.length -1 -i];
                }
                System.out.println(new String(charsFb));
            }
        }
    }

    输出结果:

     果然,快多了,而且内存占用也少了。

    Over......

  • 相关阅读:
    PHP WAMP关闭notice等提示
    PowerDesigner 逆向工程 从SQL文件转换成PDM 从PDM转成CDM
    Servlet 各种path路径比较
    数据库一对一的两种关联 主键关联和外键关联
    Java Timer定时器
    VS2010彻底卸载
    VS2010每次编译都重新编译整个工程的解决方案
    DbgPrint/KdPrint输出格式控制
    error TRK0002: Microsoft Visual Studio 10.0VCinlink.exe Access is denied.
    WinDbg F9时“code not found breakpoint not set”
  • 原文地址:https://www.cnblogs.com/gjmhome/p/15068397.html
Copyright © 2020-2023  润新知