zoukankan      html  css  js  c++  java
  • LeetCode 344. Reverse String

    problem:

    Write a function that takes a string as input and returns the string reversed.
    
    Example:
    Given s = "hello", return "olleh". 

    first:

    class Solution {
        public String reverseString(String s) {
            StringBuilder reversed = new StringBuilder();
            char[] array = s.toCharArray();
            for(int i=array.length-1;0<=i;i--){
                reversed.append(array[i]);
            }
            return reversed.toString();
        }
    }

    result:

    second try:

    class Solution {
        public String reverseString(String s) {
            StringBuffer reversed = new StringBuffer();
            char[] array = s.toCharArray();
            for(int i=array.length-1;0<=i;i--){
                reversed.append(array[i]);
            }
            return reversed.toString();
        }
    }

    result:

    换成StringBuffer,效果竟然一样??

    3nd:

    class Solution {
        public String reverseString(String s) {
            
            char[] array = s.toCharArray();
            char[] reversed = new char[array.length];
            for(int i=array.length-1;0<=i;i--){
                reversed[array.length-1-i]=array[i];
            }
            return new String(reversed);
        }
    }

    result:

    可见,用数组代替string和StringBuffer或StringBuilder会更快。

    4th:

    class Solution {
        public String reverseString(String s) {
            StringBuilder sb = new StringBuilder(s);
            sb.reverse();
            return sb.toString();
        }
    }

    result:

    conclusion:

    https://stackoverflow.com/questions/355089/difference-between-stringbuilder-and-stringbuffer

    根据上述链接, StringBuilder因为没有同步,会比StringBuffer更快。但为什么在leetCode上两者速度一样?莫非LeetCode做了默认优化?

    另外,第四种写法,直接用了StringBuilder的reverse方法,写起来更简单。

  • 相关阅读:
    FTP命令行工具NCFTP
    XP 通过无线网卡 建立对等网
    Silverlight WCF 压缩
    EntityFramework Linq查询
    UCS2编码转换C#
    C#7Z压缩
    c#公钥加密私钥解密和验证
    SVN global ignore pattern for c#
    典型的DIV CSS三行二列居中高度自适应布局
    VC#窗体的大小设置
  • 原文地址:https://www.cnblogs.com/hzg1981/p/8946776.html
Copyright © 2011-2022 走看看