LeetCode_344_反转字符串

题目链接

  • https://leetcode-cn.com/problems/reverse-string/

解题思路

  • 双指针法
  • 一个指针记录当前元素的下标
  • 一个指针记录当前元素 对应的倒数元素的下标
  • 因为一直数组长度,所有对应数组下标为s.length- i - 1

AC代码

class Solution {
    public void reverseString(char[] s) {
        char tmp = ' ';
        for (int i = 0; i < s.length / 2; i++) {
            tmp = s[i];
            s[i] = s[s.length - i - 1];
            s[s.length - i - 1] = tmp;
        }
    }
}

本地测试代码

package com.company;

import java.util.Arrays;

public class Solution_344 {
    public static String reverseString(char[] s) {
        char tmp = ' ';
        for (int i = 0; i < s.length / 2; i++) {
            tmp = s[i];
            s[i] = s[s.length - i - 1];
            s[s.length - i - 1] = tmp;
        }
        return Arrays.toString(s);
    }

    public static void main(String[] args) {
        System.out.println(reverseString(new char[]{'h', 'e', 'l', 'l', 'o'}));
        System.out.println(reverseString(new char[]{'H', 'a', 'n', 'n', 'h'}));
    }
}

你可能感兴趣的:(LeetCode学习之路,leetcode,字符串)