LeetCode 344. Reverse String(Java)

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

Example:
Given s = “hello”, return “olleh”.


题意:
写一个方法可以将输入的字符串反转并返回。


思路:
1.将字符串转化为字符数组;
2.对字符数组关于中间对称的元素进行交换;
3.将字符数组包装成字符串并返回。


代码:

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

你可能感兴趣的:(LeetCode)