Solution of Reverse Only Letters

本文介绍了一种在给定字符串中仅反转字母字符,同时保持其他字符位置不变的算法。通过使用双指针技术,该方法能够在O(n)的时间复杂度内完成操作,适用于如“ab-cd”或“Test1ng-Leet=code-Q!”等复杂输入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a string S, return the “reversed” string where all characters that are not a letter stay in the same place, and all letters reverse their positions.

Example 1:

Input: “ab-cd”
Output: “dc-ba”
Example 2:

Input: “a-bC-dEf-ghIj”
Output: “j-Ih-gfE-dCba”
Example 3:

Input: “Test1ng-Leet=code-Q!”
Output: “Qedo1ct-eeLg=ntse-T!”

Note:

S.length <= 100
33 <= S[i].ASCIIcode <= 122
S doesn’t contain \ or "

Ideas of solving problems

In solving this problem, we should choose two Pointers.The first pointer starts at the beginning and the second pointer starts at the end.You just have to decide if it’s a letter and reverse it.We can use ASCII code to determine whether a string is a letter or a character. The time complexity is O(n), and the space complexity is O(n). The memory consumption is 2Mb.

Code

func reverseOnlyLetters(S string) string {
	var left,right int = 0,len(S) - 1
	for left < right {
		if isLetter(S[left]) && isLetter(S[right]) {
			S = S[:left] + string(S[right]) + S[left + 1:right] + string(S[left]) + S[right + 1:]
			left++
			right--
		}
		if !isLetter(S[left]) {
			left++
		}
		if !isLetter(S[right]) {
			right--
		}
	}

	return S
}
func isLetter(a byte) bool {
	if (a >= 65 && a <= 90) || (a >= 97 && a <= 122) {
		return true
	}
	return false
}

链接:https://leetcode-cn.com/problems/reverse-only-letters/solution/917jin-jin-fan-zhuan-zi-mu-by-wang-xiao-zhu-3/
来源:力扣(LeetCode)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值