LeetCode:翻转字符数组

Write a function that reverses a string.The input string is given as an array of characters
char[].Do not allocate extra space for another array,you must do this by modifying the
input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.

Example 1:
Input:["h","e","l","l","o"]
Output:["o","l","l","e","h"]

Example 2:
Input:["H","a","n","n","a","h"]
Output:["h","a","n","n","a","H"]

题目大意:
翻转数组,空间复杂度为O(1).
利用左右双指针进行遍历,不断交换左右两边的元素.
package main

import "fmt"

func reverseString(s []byte)[]byte{
	l,r:=0,len(s)-1
	for l<r{
		s[l],s[r]=s[r],s[l]
		l++
		r--
	}
	return s

}
func main(){
	s:=[]byte{'h','e','l','l','o'}
	fmt.Printf("%v",reverseString(s))
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路上的追梦人

您的鼓励就是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值