题目描述

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

Example:

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

解法一

思路

很基础的题,用两个指针就好了。头指针初始指向字符串首,尾指针初始指向字符串尾,每次交换两个指针指向字符串位置的字符;然后头指针向后移动一位,尾指针向前移动一位;如此循环,直到头尾指针相遇。

Python

Python可以直接用语法糖了~

class Solution(object):
    def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        return s[::-1]

Java

因Java中String类型是不可变的,为了避免不必要的开销,将字符串转换为char[]后直接操作数组,最后以字符串形式返回结果。

public class Solution {
    public String reverseString(String s) {
        char[] charArray = s.toCharArray();
        for (int i = 0, j = charArray.length - 1; i < j; i++, j--) {
            char temp = charArray[i];
            charArray[i] = charArray[j];
            charArray[j] = temp;
        }
        return new String(charArray);
    }
}

C++

class Solution {
public:
    string reverseString(string s) {
        for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
            char temp = s[i];
            s[i] = s[j];
            s[j] = temp;
        }
        return s;
    }
};