917.仅仅反转字母

This commit is contained in:
游由 2022-02-23 09:50:16 +08:00
parent 807a2e1404
commit 92ec0441b5
2 changed files with 71 additions and 0 deletions

View File

@ -150,6 +150,7 @@ mod q0876;
mod q0888;
mod q0897;
mod q0912;
mod q0917;
mod q0918;
mod q0938;
mod q0947;

View File

@ -0,0 +1,70 @@
use crate::Solution;
impl Solution {
/// [917.仅仅反转字母](https://leetcode-cn.com/problems/reverse-only-letters/)
///
/// 2022-02-23 09:11:02
///
/// 给你一个字符串 `s` ,根据下述规则反转字符串:
///
/// > 所有非英文字母保留在原有位置。
/// >
/// > 所有英文字母(小写或大写)位置反转。
///
/// 返回反转后的 `s` _。_
///
/// + **示例 1**
/// + **输入:** s = "ab-cd"
/// + **输出:** "dc-ba"
/// + **示例 2**
/// + **输入:** s = "a-bC-dEf-ghIj"
/// + **输出:** "j-Ih-gfE-dCba"
/// + **示例 3**
/// + **输入:** s = "Test1ng-Leet=code-Q!"
/// + **输出:** "Qedo1ct-eeLg=ntse-T!"
/// + **提示**
/// * `1 <= s.length <= 100`
/// * `s` 仅由 ASCII 值在范围 `[33, 122]` 的字符组成
/// * `s` 不含 `'\"'` 或 `'\\'`
/// + Related Topics
/// * 双指针
/// * 字符串
/// * 👍 114
/// * 👎 0
pub fn reverse_only_letters(s: String) -> String {
if s.is_empty() {
return s;
}
let mut bytes = s.into_bytes();
let mut first = 0usize;
let mut last = bytes.len() - 1usize;
while first < last {
match (bytes[first], bytes[last]) {
(b'a'..=b'z' | b'A'..=b'Z', b'a'..=b'z' | b'A'..=b'Z') => {
bytes.swap(first, last);
last -= 1usize;
first += 1usize;
}
(b'a'..=b'z' | b'A'..=b'Z', _) => last -= 1usize,
(_, b'a'..=b'z' | b'A'..=b'Z') => first += 1usize,
_ => {
last -= 1usize;
first += 1usize;
}
}
}
String::from_utf8(bytes).unwrap()
}
}
#[cfg(test)]
mod test {
use crate::Solution;
#[test]
fn test_q0917() {
assert_eq!(Solution::reverse_only_letters("ab-cd".to_string()), "dc-ba".to_string());
assert_eq!(Solution::reverse_only_letters("a-bC-dEf-ghIj".to_string()), "j-Ih-gfE-dCba".to_string());
assert_eq!(Solution::reverse_only_letters("Test1ng-Leet=code-Q!".to_string()), "Qedo1ct-eeLg=ntse-T!".to_string());
}
}