当前位置:网站首页>字符串——344.反转字符串
字符串——344.反转字符串
2022-07-24 11:23:00 【向着百万年薪努力的小赵】
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”]
3 题目提示
1 <= s.length <= 105
s[i] 都是 ASCII 码表中的可打印字符
4 思路
对于长度为N的待被反转的字符数组,我们可以观察反转前后下标的变化,假设反转前字符数组为s[o] s[1] s[2] … sLN- 1],那么反转后字符数组为s[N - 1] s[N - 2] …s[o]。比较反转前后下标变化很容易得出s[i]的字符与s[N - 1 - i]的字符发生了交换的规律,因此我们可以得出如下双指针的解法:
- 将1eft指向字符数组首元素,right指向字符数组尾元素。
- 当1eft < right :
- 交换s[1eft]和s[right] ;
- left指针右移一位,即1eft = left + 1 ;
- right指针左移一位,即right = right - 1。
- 当1eft >= right ,反转结束,返回字符数组即可。

复杂度分析
时间复杂度:O(N)O(N),其中 NN 为字符数组的长度。一共执行了 N/2N/2 次的交换。
空间复杂度:O(1)O(1)。只使用了常数空间来存放若干变量。
5 我的答案
class Solution {
public void reverseString(char[] s) {
int n = s.length;
for (int left = 0, right = n - 1; left < right; ++left, --right) {
char tmp = s[left];
s[left] = s[right];
s[right] = tmp;
}
}
}
边栏推荐
猜你喜欢

Idea background image set

tcp 服务端接收数据处理思路梳理,以及select: Invalid argument报错 笔记

Robot framework official tutorial (I) getting started
](/img/1f/37c5548ce84b6a217b4742431f1cc4.png)
运算放大器 —— 快速复苏笔记[壹](参数篇)

ctfshow ThinkPHP专题 1

Installing Oracle Xe with Linux

DevOps及DevOps常用的工具介绍

High speed ADC test experience

【反序列化漏洞-01】序列化与反序列化简介

Self taught software testing talent -- not covered
随机推荐
Why can't memset initialize array elements to 1?
Tensor and numpy convert "suggested collection" to each other
在线客服聊天系统源码_美观强大golang内核开发_二进制运行傻瓜式安装_附搭建教程
DevOps及DevOps常用的工具介绍
What is the charm of CSDN members? What's the use of him?
只会“点点点”,凭什么让开发看得起你?
Lanqiao cup provincial training camp - commonly used STL
E2PROM read / write (xiicps) on PS side of zcu102 board
Idea background image set
Blue Bridge Cup provincial match training camp - Calculation of date
Classification and introduction of arm and series processors
Redis 100 million level data storage scheme hash slot partition
黑马瑞吉外卖之员工信息分页查询
cgo+gSoap+onvif学习总结:9、go和c进行socket通信进行onvif协议处理
Nodejs CTF Foundation
[golang] golang realizes sending wechat service number template messages
Reprint: getting started with cache coherence
MySQL query field matches the record of a rule
Semaphore详解
【10】团队协作和跨团队协作