首页 > 其他分享 >LeetCode344.反转字符串

LeetCode344.反转字符串

时间:2022-10-14 17:01:11浏览次数:80  
标签:head String 反转 chars LeetCode344 tail 字符串 指针

1.题目描述

编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 s 的形式给出。

不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。

2.示例

示例 1:

输入:s = ["h","e","l","l","o"]
输出:["o","l","l","e","h"]

示例 2:

输入:s = ["H","a","n","n","a","h"]
输出:["h","a","n","n","a","H"]

提示:

  • 1 <= s.length <= 105
  • s[i] 都是 ASCII 码表中的可打印字符

3.代码实现和思想

package com.yt.leetcode;

/**
 * @auther yt
 * @address https://www.cnblogs.com/y-tao/
 */
public class Test344 {
    public static void main(String[] args) {
        char[] chars = {};
//        String s = new String(chars);
//        System.out.println(s);//abc
        Solution344 solution344 = new Solution344();
        solution344.reverseString(chars);

    }
}

//解题思路
//创建两个指针,头指针和尾指针
//分别交换对应的两个指针指向的元素
//当头指针大于尾指针时,结束循环,即完成交换
class Solution344 {
    public void reverseString(char[] s){
        //把字符数组转换为字符串,便于求出字符数组的长度
        String chars = new String(s);
        char temp;//用于交换的临时变量
        int head = 0;
        int tail = chars.length() - 1;
        while (head < tail){
                temp = s[head];
                s[head] = s[tail];
                s[tail] = temp;
                head++;
                tail--;
        }

        for (int i = 0; i < chars.length(); i++) {
            System.out.print(s[i]);
        }

    }
}

4.来源

力扣(LeetCode)
链接:https://leetcode.cn/problems/reverse-string

标签:head,String,反转,chars,LeetCode344,tail,字符串,指针
From: https://www.cnblogs.com/y-tao/p/16792172.html

相关文章