码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: 344. Reverse String

时间:2016-08-09 13:41:17      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

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

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

题目大意就是给一个字符串,得到倒序字符串

corner case:空字符串或者字符串长度为0

 

解法一:

申请额外空间,index指向原字符串串尾,倒序构建新字符串

 

public class Solution 
{
    public String reverseString(String s) 
    {
        if (s == null || s.length() == 0)
        {
            return s;
        }
        
        String res = "";
        int index = s.length() - 1;
        
        for (; index >= 0; index--)
        {
            res += s.charAt(index);
        }
        
        return res;
    }
}

时间复杂度:n, 空间复杂度: n
超时

 

解法二:

双pointer指向头尾,直接交换字符。不需要额外空间,只用循环n/2次

public class Solution 
{
    public String reverseString(String s) 
    {
        if (s == null || s.length() == 0)
        {
            return s;
        }
        
        int left = 0;
        int right = s.length() - 1;
        char[] sChar = s.toCharArray();
        
        while (left < right)
        {
            char temp = sChar[left];
            sChar[left] = sChar[right];
            sChar[right] = temp;
            
            left++;
            right--;
        }
        
        return new String(sChar);
    }
}

 

LeetCode: 344. Reverse String

标签:

原文地址:http://www.cnblogs.com/snakech/p/5752803.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!