LeetCode: 344. Reverse String

351 查看

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);
    }
}