美文网首页
LeetCode-反转字符串

LeetCode-反转字符串

作者: G_dalx | 来源:发表于2018-09-04 22:06 被阅读0次

    编写一个函数,其作用是将输入的字符串反转过来。

    示例 1:

    输入: "hello"
    输出: "olleh"
    

    示例 2:

    输入: "A man, a plan, a canal: Panama"
    输出: "amanaP :lanac a ,nalp a ,nam A"
    

    最常用的方法toCharArray for循环从后往前遍历,存入新数组或字符串
    代码

    public static String reverse(String s)
     { 
        char[] array = s.toCharArray(); 
        String reverse = "";  //新建空字符串
        for (int i = array.length - 1; i >= 0; i--) {
               reverse += array[i]; 
           }
       return reverse; 
      } 
    

    第二种方法 StringBuffer 的reverse()方法
    代码

    class Solution {
        public String reverseString(String s) {
            if(s==null){
                return null;
            }
            if(s.length()==0){
                return "";
            }
            StringBuffer stringBuffer=new StringBuffer(s);
            stringBuffer.reverse();
            return stringBuffer.toString();
        }
    }
    

    相关文章

      网友评论

          本文标题:LeetCode-反转字符串

          本文链接:https://www.haomeiwen.com/subject/aionwftx.html