Open carloscn opened 1 year ago
准备一个vec,用于容纳返回的字符串。准备两个index变量,一个叫做left_index, right_index。遍历字符串:
pub fn reverse_only_letters(s: String) -> String
{
let mut ret_str:String = String::new();
let mut left_index:usize = 0;
let mut right_index:usize = s.len();
let mut ret_chars:Vec<char> = s.chars().collect();
if right_index < 1 {
return ret_str;
}
right_index -= 1;
while left_index < right_index {
while !ret_chars[left_index].is_alphabetic() &&
left_index < right_index {
left_index += 1;
}
while !ret_chars[right_index].is_alphabetic() &&
left_index < right_index {
right_index -= 1;
}
if left_index < right_index {
ret_chars.swap(left_index, right_index);
left_index += 1;
right_index -= 1;
}
}
let s:String = ret_chars.into_iter().collect();
ret_str.push_str(&s);
return ret_str;
}
问题描述
给你一个字符串 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 不含 '\"' 或 '\'
来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/reverse-only-letters