题目

Write a function that takes a string as input and returns the string reversed.

Example:
Given s = "hello", return "olleh".

分析

字符串反转

解答

(7ms)

String中"+"进行字符串连接的处理步骤实际上是通过建立一个StringBuffer,然后调用append(),最后再将StringBuffer toString();

由此,String的连接操作就比StringBuffer多出了一些附加操作,当然效率上要打折扣。

此处使用StringBuffer.append,若改为用String的"+"连接,则出现超时错误

public class Solution {
    public String reverseString(String s) {
        StringBuffer strbuf = new StringBuffer();
        for (int i = s.length() - 1; i > -1; i--){
            strbuf.append(s.charAt(i));
        }
        return strbuf.toString();
    }
}


(3ms√)

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

相关文章:

  • 2021-07-11
  • 2021-09-13
  • 2021-10-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-12
  • 2021-04-24
  • 2022-02-12
相关资源
相似解决方案